Skip to content

A better (native) way for AJAX calls

If you have developed a web apps in past few years, you certainly came around asynchronous requests, also know as AJAX. There was the really clunky way using the native XMLHttpRequest and a bit more convenient way using jQuery’s $.ajax() function. But the problems like callback hell were all the same between those, as the jQuery implementation is just shadowing XMLHttpRequest.

Fetch is a new way to do perform AJAX requests, and the underlying API is working with Promises, a much cleaner and simpler API. Here are some usage examples:

GET Request:

fetch(`/api/function`).then(function(resp){
    return resp.json();
}).then(function(data) {
    //Use returned data
}).catch(function(e){
    //Process error
});

POST request:

fetch(`/api/function`, {
    method: "POST"
}).then(function(resp) {
    return resp.json();
}).then(function(data) {
    //Use returned data
}).catch(function(e){
    //Process error
});

POST Request with data and headers:

fetch(`/api/function`, {
    method: "POST",
    body: JSON.stringify({fkey: "fkey-example"}),
    headers: { "Content-type": "application/json; charset=UTF-8" }
}).then(function(resp) {
    return resp.json();
}).then(function(data) {
    //Use returned data
}).catch(function(e){
    //Process error
});

(source)

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.