post_from_link javascript tip

December 13, 2008 | In: development, javascript, ruby

I wrote this the other day. Thought someone might find it useful. Will let you do a POST request from a link. Good for delete buttons, since we all know your not supposed to let users delete things from a get request… right?! ;)

Basically it takes your url & params and dynamically builds the DOM for the form and then submits it.

Requires that you include prototype.js.

Here is an example link. You just pass the url you wish to submit to and an associative array of the params.

post the request

Here is the js function. Include this in the head of your page.

/*
* Dynamically creates a form based on args and submits it to the given url
* @param {Object} url
* @param {Object} params
*/
function post_from_link(url,params){
   var form = new Element('form', { action: url, method: 'POST' });
   for(param in params){
       var hidden = new Element('input', {type:'hidden', name:param, value:params[param]});
       form.insert(hidden);
   }
   document.body.appendChild(form);
   form.submit();
}
Bookmark and Share
blog comments powered by Disqus

Flickr Pics

13th and washington NYC13th and 9th NYC1st st Jersey CityIMG_2813IMG_2814_2IMG_2816IMG_2815Photo_011908_001Photo_122807_001Photo_121107_001