GoodBye XMLHttpRequest; AJAX with fetch API (with Demo)

AJAX is a crucial part of any Web App. The primary way to do AJAX is through XMLHttpRequest. JavaScript has new fetch API which will remove the need to use the weird XMLHttpRequest

GoodBye XMLHttpRequest; AJAX with fetch API (with Demo)

These days, AJAX is a crucial part of any Web App. The primary way to do AJAX is through XMLHttpRequest.

JavaScript has new fetch API which will remove the need to use the weird XMLHttpRequest where most of the time, nothing is XML.

fetch API has very simple and generic interface and is available in global scope.

Demo


fetch() needs one mandatory argument which is either the URL of the resource that needs to be fetched or the Request object which will have url property.

fetch() returns a Promise which resolves to the Response of the Request.

The Promise will be failed/rejected only if the fetch failed because of reasons like network connectivity etc.; which means even if the response is HTTP error like 5xx, 4xx etc, you need to handle it by yourself.

Following is the basic example of the fetch() to fetch JSON:

fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(console.log)

Or the image with Request Object:

const url = '//res.cloudinary.com/time2hack/image/upload/css-css3-flexbox-layout.png';

const request = new Request(url);
fetch(request)
    .then(response => response.blob())
    .then(blob => {
        var file = new FileReader();
        file.onload = (e) => {
            return e.target.result
        }
        file.readAsDataURL(blob);
    })
    .then(dataUrl => {
        const image = document.createElement('img')
        image.src = dataUrl;
        image.setAttribute('style', 'max-height: 200px;');
        document.body.appendChild(image)
    });

Use of Request object is an advanced usage when you want to send more headers, or different method of Request.

fetch sends a GET request by default.


Lets see an example of POST method:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST'
})
  .then(response => response.json())
  .then(console.log)

For POST method with Request Object, we can achieve that as follows:

const url = 'https://jsonplaceholder.typicode.com/posts'
const request = new Request(url, {
  method: 'POST',
  headers: headers,
  body: new FormData(document.querySelector('#profileForm'))
});

fetch(request)
  .then(response => response.json())
  .then(data => { console.log(data); })

But you don't need to have form in DOM, you can build the formData manually as well, like in following example:

const form = new FormData();
form.append('name', 'Time to Hack');
form.append('url', 'https://time2hack.com');

const url = 'https://jsonplaceholder.typicode.com/posts'
const request = new Request(url, {
  method: 'POST',
  headers: headers,
  body: form
});

fetch(request)
  .then(response => response.json())
  .then(data => { console.log(data); })

Or, what if you need to send the JSON data? following way, you can do so:

const url = 'https://jsonplaceholder.typicode.com/posts'
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const request = new Request(url, {
  method: 'POST',
  headers: headers,
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
});

fetch(request)
  .then(response => response.json())
  .then(data => { console.log(data); })

You can also upload the files with the FormData API; following example demonstrates that:

<!-- Form -->
<form id="profileData">
  <input type="text" id="name" name="name" placeholder="Name" />
  <input type="text" id="url" name="url" placeholder="URL" />
  <input type="file" id="photo" name="photo" placeholder="Photo" />
</form>
// Form Handling by the FormData API
const form = new FormData(document.querySelector('#profileData'));
form.append('from', 'Time to Hack');

const url = 'https://jsonplaceholder.typicode.com/posts'
const request = new Request(url, {
  method: 'POST',
  headers: headers,
  body: form
});

fetch(request)
  .then(response => response.json())
  .then(data => { console.log(data); })

You can read a brief about FormData API here:
FormData API: Handle Forms like Boss ? - Time to Hack
Handling Forms has always been confusing as there are many ways to do so. Let’s take a look at the cool features of FormData API to handle Forms.

And similarly you can code up for all the REST API.

If you are concerned with the Browser compatibility, these two polyfills are more than enough to make fetch your primary choice for your next Front End Project.


References

Can I Use fetch? Data on support for the fetch feature across the major browsers from caniuse.com.


Demo


Let me know through comments ? or on Twitter at @heypankaj_ and/or @time2hack

If you find this article helpful, please share it with others ?

Subscribe to the blog to receive new posts right to your inbox.