Thursday, March 24, 2011

POST Method request Using JavaScript



How to simulate the below in javascript ?

action=http://example.com/ method=POST
input type=hidden name=q value=a
How to call the javascript function :

post_to_url
('http://example.com/', {'q':'a'});

function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.

// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);

for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);

form.appendChild(hiddenField);
}

document.body.appendChild(form); // Not entirely sure if this is necessary
form.submit();
}


Hope this helped someone.