Tutorials‎ > ‎

[Javascript] Easy AJAX Call Using Browser's Fetch API

posted Nov 21, 2017, 3:56 AM by Benedictus Jason Reinhart

Fetch API allows you as developer to make an AJAX call (or XMLHttpRequest) natively in browser without additional libraries like jQuery and such. The main advantage of using Fetch API is that it uses the Promise feature, avoiding dependencies and callback hell. If you are not familiar with promises, you can learn about it here.

The Fetch API is pretty accessible with 78% global support according to caniuse. Moreover, it helps you as developer to implement AJAX call as many libraries implement them differently. To better support old browsers, there’s a fetch polyfill library here along with the promise polyfill library here.

 The syntax is pretty straightforward:

fetch(url, options)

The function will return a promise which you can chain using then method, for example:

fetch('https://jsonplaceholder.typicode.com/posts/1')

.then(r => r.json())

.then(r => console.log(r.title))

By default, the fetch API will make a HTTP GET request to the provided URL. The .json() method will parse the response body into a JSON object. The headers are automatically set by the browser such as Accept (default is *), Content-Type (default is text/html), etc.

In real use case, you won’t be messing with only GET request and only text/html content type. In that case, the second parameter options plays in. You can specify the request method, most headers (some headers are restricted such as Origin), mode (CORS or same-origin), credentials, etc.

For example, if we want to make a new post:

fetch('https://jsonplaceholder.typicode.com/posts', {

       method: 'post',

       headers: {

              'Content-Type': 'application/json',

              Accept: 'application/json',

       },

       body: JSON.stringify({

              title: 'Hello world',

              body: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',

}),

}).then(r => {

       alert('Create post success!');

});

Here, we specify the request method to POST, set the headers, and put the data to be sent in the body property. If the server recognizes application/json content type and we sure that the response is also application/json, then this will work for sure. 

In authorized environment, you might want to call an API by also sending the default credentials, usually using session cookie. By default, the Fetch API does not send your credentials like session cookie (such as .PHPSESSIONID and .ASPXAUTH). This means that whenever you request something to the server, it cannot recognize who you are, resulting in an anonymous and/or unauthorized call. To solve this, add the credentials property to the options parameter.

fetch('https://jsonplaceholder.typicode.com/posts', {

       method: 'post',

       credentials: 'include',

       headers: {

              'Content-Type': 'application/json',

              Accept: 'application/json',

       },

       body: JSON.stringify({

              title: 'Hello world',

              body: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',

}),

}).then(r => {

       alert('Create post success!');

});

 

The credentials property accepts 3 kind of values:

·         include à session cookie will be sent to EVERY kind of request regardless of origin.

·         same-origin à credentials only sent with the same origin policy.

·         omit à no credentials are sent.

Starting with Chrome 50, you can also put FederatedCredential and PasswordCredential instances to credentials property.

Comments