/ javascript

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 is failed/rejected only if the fetch failes because of reasons like network connectivity etc.; which means even if the response is errorful 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 a 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 manully 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>
  <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();
form.append('name', document.querySelector('#name'));
form.append('url', document.querySelector('#url'));
form.append('photo', document.querySelector('#photo'));

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); })

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


Please provide yor valuable feedback/suggestions in the comments below.