Blog postModern AJAX with fetch API

Modern AJAX with Fetch API

Published September 04, 2018

Fetch is the modern way to perform AJAX when working with JavaScript. Instead of writing cumbersome AJAX code or using libraries such as jQuery and Angular, the new JavaScript standard offers a more compact, modern, and flexible syntax.

There's a lot to learn about the Fetch method in JavaScript, but in this tutorial, we'll learn the essentials of requesting the data from the backend with a GET request, as well as POSTing the data to the server side.

In this tutorial you will learn:

  1. How to get data with Fetch
  2. How to post data with Fetch
  3. Which is better old-time AJAX vs. Fetch

# 1. How to get data with Fetch

The only parameter that is essential to pass to the fetch() method is the URL from which we want to get the data. For example:

fetch('https://phpenthusiast.com/dummy-api/')

The URL is for a very simple API service that returns a random number in a range of numbers. A simple GET request will return a random number between 1 and 10. Alternatively, you can send a POST request with a minimum and maximum value, and receive a random number in the range. This tutorial will show both options in action.

The fetch() method returns a promise (and if you are not familiar with the concept, you can learn about JavaScript promises in the following tutorial). Therefore, it can return one of two possible responses, success or failure:

fetch('https://phpenthusiast.com/dummy-api/')
.then((res) => {
    // do something with the response
})
.catch((error) => console.log(error))

In the case of failure, the response will be handled by the catch block, and in case of success the response will be handled by the then block. You can see for yourself by following the instructions:

  1. Open the Chrome developer tools (Ctrl + Shift + I on Windows/Linux, Cmd + Opt + I on a Mac).
  2. Click the "Console" tab.
  3. Paste the code:
    fetch('https://phpenthusiast.com/dummy-api/')
    .then((res) => {
        // Your code here
    })
    .catch((error) => console.log(error))
  4. Hit enter.
  5. Click the "Network" tab to see all of your requests, and then press the "XHR" tab to see the AJAX requests.
  6. Press the name "dummy-api/", and on the right side you can see the request headers:

    get request with javascript fetch method

    A "200" response code indicates that the data is received and the operation is performed.
  7. And there's also the body of the response which contains the random number that you can see by clicking the "Preview" tab:

    The body of the response when using the fetch api

    • When you execute the request, you will probably get a different value, because the API provides a random number.
    • Here I use the console to demonstrate the easiness of the process, but a more practical approach would be to put the code inside a JS script.
  8. To extract the data from the response body, you need to use the methods that the Fetch API provides. In this example, since you expect a JSON formatted response, you need to use the json() method:
    fetch('https://phpenthusiast.com/dummy-api/')
      .then((res) => {
        return res.json();
      })
      .catch((error) => console.log(error))
  9. The json() method also returns a promise so you need to chain another then block:
    fetch('https://phpenthusiast.com/dummy-api/')
      .then((res) => res.json())
      .then((data) => console.log(data))
      .catch((error) => console.log(error))
  10. Since the code prints the result to the console, you can see the result by opening the console:

    open the console to see the result of sending a fetch request

It's as simple as that.

# 2. Posting data with the Fetch

To post the data to the server, you need to add a JSON object as the second parameter that you pass to the fetch() method:

fetch('https://phpenthusiast.com/dummy-api/', {
    method : 'post'
})
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error))

Except for the "method" field, you also need to provide the "body" field with the actual data that you want to send to the server:

fetch('https://phpenthusiast.com/dummy-api/', {
    method : 'post',
    body: JSON.stringify({min: 1, max: 100})
})
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error))

You need to use the JSON.stringify() method to make a string out of the data because you can't send objects.

The fields "mode" and "headers" are not essentials, yet you need to know about them:

fetch('https://phpenthusiast.com/dummy-api/', {
    method : 'post',
    mode:    'cors',
    headers: {
      'Content-Type': 'application/json',  // sent request
      'Accept':       'application/json'   // expected data sent back
    },
    body: JSON.stringify({min: 1, max: 100})
})
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error))
  • The headers field specifies the data type for the sent data (Content-Type) as well as the received data (Accept).
    • The default value for the "mode" field is "cors" which allows it to send requests to a different website from the one that sends the request. For example, send requests to Facebook, Google, or other API providers.

      Another condition is that the service provider needs to configure the server to allow data exchange with external apps. If the API provider doesn't configure the server, you can use the "no-cors" option, which will allow the sending of data to the server, but without getting a response back. The "same-origin" option requires the request to be on the same server.

# Which is better old-time AJAX vs. Fetch

As you learned in this tutorial, the Fetch method is more friendly and modern than the old AJAX, and thus the fetch() method will eventually replace the old code, but it will take years. Until that happens, you need to overcome the problem of older browsers which don't support the new standard, especially the explorers and mobile browsers. You can solve the problem by using a polyfill. To find out which browsers do support the standard, you can go to https://caniuse.com/ which is a site worth knowing if you are uncertain about the chances that a particular feature will not work in your client's favorite browser. As of September 2019, the support for the fetch method is quite widespread:

can i use fatch api in the browsers