Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

I am trying to direct my browser to a different page. If I wanted a GET request, I want to say:

document.location.href = 'http://example.com/q=a';

But the resource I am trying to access is not responding properly unless I use a POST request. If this were not dynamically generated, I might use the HTML

<form action="http://example.com/" method="POST">

  <input type="hidden" name="q" value="a">

</form>

Then I will just submit the form from the DOM.

But what I like JavaScript code to allow me to say:

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

What is the best cross-browser implementation?

1 Answer

0 votes
by (13.1k points)

You can dynamically create input tags in a form and submit the form like this:

/**

 * 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 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';

      hiddenField.name = key;

      hiddenField.value = params[key];

      form.appendChild(hiddenField);

    }

  }

  document.body.appendChild(form);

  form.submit();

}

Example:

post('/contact/', {name: 'Dale Steyn'});

Want to learn Java? Check out the Java certification from Intellipaat. 

Related questions

+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 28, 2021 in Web Technology by Jake (7k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...