POST data via Ajax with the Javascript Fetch and FormData APIs

Learn how to make POST requests with Ajax and Fetch, also using FormData, the Javascript API for building objects with form data.

In this article we are going to carry out a workshop on sending data by POST, from Javascript, with Ajax and using the Fetch API, which is the most modern and simple mechanism to make asynchronous calls from Javascript.

In addition, you will be able to learn about another very useful Javascript API in browsers called FormData, which we will use to easily build objects from the data of a form.

Our goal is not so much to explain fetch from scratch, as it is a topic we have already covered before. Rather, we want to see a specific use case for fetch that we will use when we want to send data via POST to a web server. However, it should be noted that the main novelty of Fetch is the possibility of using promises, which makes it quite simple to work with asynchronous calls. For basic information about this API we recommend reading the article.

Knowing FormData

The first thing you need to know to submit form data is to retrieve the information typed into the fields of one of the forms on the page. For this, in Javascript we have the FormData objects.

FormData allows us to have an object with all the form data, with key value pairs. Where the key is the “name” of the form field and the value is its “value” property.

Receiving all the data from a form is as simple as executing the FormData constructor, sending as a parameter the form object that we want to use to retrieve its data. It would be something like this:

const data = new FormData(document.getElementById(‘form’));

As you can see, we create a new FormData object from the form with id “form”. In the constant “data” we will then have that FormData object.

Send data by POST with Fetch

Now we can use this object to send the data by POST. This part is very easy, as we just have to set the method to “POST” and pass the data in the request body. You would do it with code like this:

fetch(‘../post.php’, { method: ‘POST’, body: data })

Remember that for the request to be produced you have to write the “then” of the fetch call, because until you have defined what you want to do with the response of the Ajax call, the browser will not perform any action.

The complete code of our Ajax call could look something like this:

const data = new FormData(document.getElementById(‘form’)); fetch(‘../post.php’, { method: ‘POST’, body: data }) .then(function(response) { if(response.ok) { return response.text() } else { throw “Error in Ajax call”; } }) .then(function(text) { console.log(text); }) .catch(function(err) { console.log(err); });

Compose POST submission data without the need for a form

It could happen to you that you need to send data by POST but that you do not have a form on the page where the user has written that data. That is, generate form data from scratch, with variables or data that you have in Javascript.

This is perfectly possible, although it is somewhat more related to the use of the FormData object than to the actual Ajax call with Fetch. We do it in two steps.

  1. We create an empty FormData object, simply by passing the empty parentheses to the FormData constructor.
  2. We create all the arbitrary data with the append() method that receives the data to be added to the FormData, with its key/value pair.

The code will look like you can see below.

const data = new FormData(); data.append(‘company’, ‘WebDevelopment.com’); data.append(‘CIF’, ‘ESB00001111’); data.append(‘professional_training’, ‘ITSchool’); fetch(‘../post.php’, { method: ‘POST’, body: data }) .then(function(response) { if(response.ok) { return response.text() } else { throw “Error in Ajax call”; } }) .then(function(text) { console.log(text); }) .catch(function(err) { console.log(err); });

As you can see, the fetch part doesn’t have any variation with the previous example. We’re just creating the empty FormData and adding the data via its append() method. It’s as simple as that.

Construct the submission data with URLSearchParams

Another possible alternative is to use a URLSearchParams object, which will serve us exactly the same as FormData. The only noticeable difference is the constructor.

const data = new URLSearchParams(“name=miguel angel&nationality=spanish”);

As you can see, this constructor receives all the data you want to add, in URL format, with key/value pairs separated by the “&” character.

You can send them in the same way as always:

fetch(‘../post.php’, { method: ‘POST’, body: data })

URLSearchParams also allows you to use the append() method to add parameters or values ​​to the data that you will send via POST. It’s also identical to what you do with FormData.

data.append(‘anotherData’, ‘another value’);

We leave here the complete example code with URLSearchParams, in case someone gets lost, although it is traced to what we had seen previously.

const data = new URLSearchParams(“name=miguel angel&nationality=spanish”); data.append(‘anotherData’, ‘another value’); fetch(‘../post.php’, { method: ‘POST’, body: data }) .then(function(response) { if(response.ok) { return response.text() } else { throw “Error in Ajax call”; } }) .then(function(text) { console.log(text); }) .catch(function(err) { console.log(err); });

conclusion

We hope that this list of alternatives will help you to send data by the POST method to the server, using the Fetch API, which is the most modern way of working with Ajax in Javascript.

You will receive the data on the server by the traditional method. For example, in PHP you would use the $_POST superglobal array.

Just one more detail. Remember to use the to ensure compatibility with older browsers, if necessary for your project.

See also  Create SSH keys
Loading Facebook Comments ...
Loading Disqus Comments ...