JavaScript post request like a form submit JavaScript post request like a form submit javascript javascript

JavaScript post request like a form submit


Dynamically create <input>s in a form and submit it

/** * sends a request to the specified url from a form. this will change the window location. * @param {string} path the path to send the post request to * @param {object} params the parameters to add to the url * @param {string} [method=post] the method to use on the form */function post(path, params, method='post') {  // The rest of this code assumes you are not using a library.  // It can be made less verbose if you use one.  const form = document.createElement('form');  form.method = method;  form.action = path;  for (const key in params) {    if (params.hasOwnProperty(key)) {      const hiddenField = document.createElement('input');      hiddenField.type = 'hidden';      hiddenField.name = key;      hiddenField.value = params[key];      form.appendChild(hiddenField);    }  }  document.body.appendChild(form);  form.submit();}

Example:

post('/contact/', {name: 'Johnny Bravo'});

EDIT: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the hasOwnProperty check to fix any inadvertent bugs.


This would be a version of the selected answer using jQuery.

// Post to the provided URL with the specified parameters.function post(path, parameters) {    var form = $('<form></form>');    form.attr("method", "post");    form.attr("action", path);    $.each(parameters, function(key, value) {        var field = $('<input></input>');        field.attr("type", "hidden");        field.attr("name", key);        field.attr("value", value);        form.append(field);    });    // The form needs to be a part of the document in    // order for us to be able to submit it.    $(document.body).append(form);    form.submit();}


A simple quick-and-dirty implementation of @Aaron answer:

document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';document.getElementById("dynForm").submit();

Of course, you should rather use a JavaScript framework such as Prototype or jQuery...