JavaScript Post Request Like a Form Submit

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.

Form submit vs. Javascript POST Request

I met similar problem when I was building the back-end(using Node&Express.js) and front-end(Angular.js) separately using JSON apis. And it took 12 hours to find the reason why not working with html forms.

The problem was on the back-end side, when you submit using jquery $.post, Content-type is application/json but when you submit using html form Content-type is application/form-data.

You can test the APIs using postman, if you select the content-type as form-data that api will not work.

So to solve the problem, you have to rebuild backend apis to be compatable with Content-type application/form-data.

Additionally in my case, I used body-parser node package to analyze form data.

How to pass form data using POST method and JS submit()?

Just have a form and submit it.

form = document.forms[0] //assuming only form.
form.submit();


EDIT: OP has clarified question

Specify a method attribute on your form.

<form name="myform" action="" method="POST">

It will cause the form to be submitted as a POST.

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.

What is the difference between post api call and form submission with post method?

There are multiple ways to submit a form from the browser:

  1. HTML form, submit button, user presses submit button, no Javascript involved.
  2. HTML form in the page, Javascript gets DOM element for the form and calls .submit() method on the form object.
  3. Ajax call using the XMLHttpRequest interface with the POST method and manually sending appropriate form data.
  4. Ajax Fetch call with the POST method and manually sending appropriate form data.

With #1 or #2, the browser sends the form and the browser will pay attention to redirects and will display the form response (whether redirected or not) in the browser.

With #3 and #4, the form is sent via Javascript and the response comes back to your Javascript. #3 does not process redirects. #4 has an option to process redirects. Here's more info on each of the above options. #3 and #4 do not affect the browser display is not affected at all unless you program your own Javascript to process the request and affect the browser display (either by inserting content or setting window.location to a new URL.


Here's some more info on the above schemes:

Programmatic Ajax calls with XMLHttpRequest do not process redirects or the response from the Ajax call in any way. They just return that response to YOUR Javascript. Keep in mind that a redirect is just one specific type of response you can get back from an Ajax call. This is different than a browser submitted form POST.

Programmatic Ajax calls with the fetch() interface offer an option to follow redirects automatically. See the redirect option here. But, even in this case, all the fetch() interface does is get the contents of the redirected URL. It does not cause the browser page to change. To so that, you would have to write your own Javascript code to either see the 3xx redirect response and then set window.location to the new redirect URL. Or, you would have to let the interface follow the redirect automatically and then do something with the new redirected content that it will return to your Javascript.

These programmatic requests different than letting the browser submit a form for you. In the browser submitted case (without using Javascript to submit the form), the browser follows redirects and updates the display in the browser based on whatever content is returned from the form response.

When you submit a form via Ajax, the browser does nothing automatically with the server response. That response goes back to your Javascript and your script decides what to do with it. If you want your script to follow redirects, then you have to examine the response, see if it's a 3xx status, get the new URL from the appropriate header and set window.location to that new URL. That will then cause the browser to display the redirect page. But, you have to either program that yourself or find an Ajax library that offers a feature to do it form. A standard Ajax call just returns the form POST response back to your Javascript - that's all. Your script has to process that response and decide what to do next.

I am confused, that I cannot call gateway using post API cause it won't redirect to new page

You can. You just need to write your own Javascript to process the response from the programmatic API call and, if its a 3xx redirect, then set window.location to the new URL to instruct the browser to load the new redirected page.

Can a HTML button perform a POST request?

This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.

<form action="" method="post">
<input type="submit" name="upvote" value="Upvote" />
</form>


Related Topics



Leave a reply



Submit