Submitting a form with the Fetch API

If you are like me, you almost never directly use XMLHttpRequest – we use a library. Now is a good time to reexamine using a library. While we are at it, let’s look forward on making remote requests using the new Fetch API. Fetch gives you more control and uses modern JavaScript patterns like Promises.

Setting up the POST request

You have three things you should setup (in addition to the URL) in your request for submitting a form via the POST method.

  1. The method needs to be set to POST.
  2. The Accept header should be set to format you expect back. In this example, it is set to application/json. This is optional, but it is recommended.
  3. The body of the request needs to have the form data in the proper format: XML, JSON or multipart/form-data. You can use the FormData class to format it as multipart/form-data which is the format the browser would normally submit a form as.

Additionally depending on your requirements, you may need to set other options such as other request headers, caching rules, CORS settings, and even how redirects are to be handled.

Sending the request

Sending the request is straightforward: give fetch a URL and the options from the previous step, get a promise back. The promise will resolve with a Response object.

fetch(url, options): Promise<Response>

  • url – the URL to make the call to
  • options – the request options from the step before

Receiving the response

The response will include more than just the body, it carries the headers and more. If you use the Network tab in Chrome Developer Tools to inspect a response, you will be familiar then with the contents of the Response object.

Because you want JSON payload, you can use the .json() method to deserialize JSON data into JavaScript.

Live example

Polyfills

The fetch API is still in the early stages of being adopted by browsers. As such, the recent version of browsers support it, with the except of Safari. For backwards compatibility, Polyfill.io provides a polyfill. (Polyfill.io is a useful service because it uses browser detection to only send the polyfill to those browsers that need it.)

<script src="https://cdn.polyfill.io/v1/polyfill.min.js?features=fetch,Promise">
</script>

Learn more about the Fetch API