Fetch API for Easier Ajax Requests

If you ever used the XMLHttpRequest, you will be happy to know about the new Fetch API, which simplifies the request of resources over the network. The new API defines three new objects that are Header, Request, and Response.

“The Header” contains the headers information about HTTP requests allowing developers to set custom headers. “The Request” represents the request made to the server to retrieve a resource. “The Response” as its name indicates, represents the response with data that comes from the server after a request.

The fetch API includes the fetch function, which in its most basic form, just takes an URL of the resource to retrieve. The fetch function is probably the one you will use the most in your projects. So, let’s take a look at it, but first it is better to create an example with the XMLHttpRequest object for comparison. Assuming that we have a data.txt file on the server that contains “Hello World”.

Ajax Example

var xhr = new XMLHttpRequest();

xhr.open('GET','data.txt');
xhr.send();

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(/200|304/.test(xhr.status)){
            console.log(xhr.responseText);
        } else {
            console.log('there was an error');
                }

        }
}

The problem with the XMLHttpRequest object is that it does not support promises natively. So, in order to work with the XMLHttpRequest object, you need to wrap it with a promise. Moreover, you have to worry about what state and what type of status is coming from the server. With the use of fetch, you don’t need that in the majority of the cases. For example, this is the same Ajax request using fetch:

Ajax Example Using Fetch API

fetch('data.txt').then(function(response){
    if(response.ok){
        return response.text();
    } else {
        return 'there was an error';
    }
}).then(function(data){
    console.log(data);
});

The code is very self explanatory. It uses fetch to return the information stored in data.txt. Once the information is returned, it checks if the response was successfully (OK) and display the content on the console. If it was an error with the response, we display “There was a problem!”. For more information about this new API, please visit:

Teylor Feliz
Teylor Feliz

Teylor is a seasoned generalist that enjoys learning new things. He has over 20 years of experience wearing different hats that include software engineer, UX designer, full-stack developer, web designer, data analyst, database administrator, and others. He is the founder of Haketi, a small firm that provides services in design, development, and consulting.

Over the last ten years, he has taught hundreds of students at an undergraduate and graduate levels. He loves teaching and mentoring new designers and developers to navigate the rapid changing field of UX design and engineering.

Articles: 182