JavaScript post request like a form submit


I'm trying to direct a browser to a different page. If I wanted a GET request, I might say

document.location.href = '';

But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML

<form action="" method="POST">
  <input type="hidden" name="q" value="a">

Then I would just submit the form from the DOM.

But really I would like JavaScript code that allows me to say

post_to_url('', {'q':'a'});

What's the best cross browser implementation?


I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with XMLHttpRequest, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.

6/15/2020 8:04:16 PM

Accepted Answer

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 paramiters 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 wordy 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'; = key;
      hiddenField.value = params[key];




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.

5/3/2019 8:47:35 PM

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);


    // The form needs to be a part of the document in
    // order for us to be able to submit it.

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

document.body.innerHTML += '<form id="dynForm" action="" method="post"><input type="hidden" name="q" value="a"></form>';

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


Using the createElement function provided in this answer, which is necessary due to IE's brokenness with the name attribute on elements created normally with document.createElement:

function postToURL(url, values) {
    values = values || {};

    var form = createElement("form", {action: url,
                                      method: "POST",
                                      style: "display: none"});
    for (var property in values) {
        if (values.hasOwnProperty(property)) {
            var value = values[property];
            if (value instanceof Array) {
                for (var i = 0, l = value.length; i < l; i++) {
                    form.appendChild(createElement("input", {type: "hidden",
                                                             name: property,
                                                             value: value[i]}));
            else {
                form.appendChild(createElement("input", {type: "hidden",
                                                         name: property,
                                                         value: value}));

Rakesh Pai's answer is amazing, but there is an issue that occurs for me (in Safari) when I try to post a form with a field called submit. For example, post_to_url("",{ submit: "submit" } );. I have patched the function slightly to walk around this variable space collision.

    function post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        //Move the submit function to another variable
        //so that it doesn't get overwritten.
        form._submit_function_ = form.submit;

        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._submit_function_(); //Call the renamed function.
    post_to_url("", { submit: "submit" } ); //Works!

No. You can't have the JavaScript post request like a form submit.

What you can have is a form in HTML, then submit it with the JavaScript. (as explained many times on this page).

You can create the HTML yourself, you don't need JavaScript to write the HTML. That would be silly if people suggested that.

<form id="ninja" action="" method="POST">
  <input id="donaldduck" type="hidden" name="q" value="a">

Your function would just configure the form the way you want it.

function postToURL(a,b,c){
   document.getElementById("ninja").action     = a;
   document.getElementById("donaldduck").name  = b;
   document.getElementById("donaldduck").value = c;

Then, use it like.


But I would just leave out the function and just do.

document.getElementById('donaldduck').value = "a";

Finally, the style decision goes in the ccs file.


Personally I think forms should be addressed by name but that is not important right now.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]