7 different ways to make AJAX calls in JavaScript in 2019

Happy New Year 2019! I know I am a bit late but better late than never! πŸ˜ƒ

My new year resolution is to write something every day, even if it's something basic. Out of curiosity, I have been revisiting various ways to make API calls in JS in 2019. In this post, I'll summarize my findings and list various options to make AJAX calls. To keep it simple, let's focus on what they are, their syntaxes and some pros and cons of each option.

XHR

Ajax is the traditional way to make an asynchronous HTTP request. The XMLHttpRequest object can be used to exchange data with a web server.

Syntax

GET Request

const Http = new XMLHttpRequest();
const url='http://example.com/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}

POST Request

var xhr = new XMLHttpRequest();
xhr.open("POST", '/user', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("name=Ipseeta&id=1");

Fetch API

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

Syntax

The fetch method takes a mandatory request path as argument and returns a Promise.

GET Request

fetch('https://www.example.com', {
        method: 'get'
    })
    .then(response => response.json())
    .then(jsonData => console.log(jsonData))
    .catch(err => {
            //error block
        }

POST Request

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

Pros

  1. It’s flexible and easy to use
  2. Callback hell is avoided by Promises
  3. Supported by all modern browsers
  4. Follows request-response approach

Cons

  1. Doesn't send cookie by default
  2. CORS is disabled by default

jQuery

jQuery is a fast, small, and feature-rich JavaScript library.

Syntax

You’ll need to include the jQuery library in your project to get started.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

GET Request

$.ajax({
    url: '/users',
    type: "GET",
    dataType: "json",
    success: function (data) {
        console.log(data);
    },
    error: function (error) {
        console.log(`Error ${error}`);
    }
});

POST Request

$.ajax({
    url: '/users',
    type: "POST",
    data: {
        name: "Ipseeta",
        id: 1
    },
    dataType: "json",
    success: function (data) {
        console.log(data);
    },
    error: function (error) {
        console.log(`Error ${error}`);
    }
});

Pros

The good thing about jQuery is that you will find tons of support and documentation.

Cons

If you are already using a state management library like React, Vue etc, then using jQuery just for ajax is overkill.

Axios

Promise based HTTP client for the browser and node.js It lets you make HTTP requests from both the browser and the server.

Syntax

You can install through npm install axios and import import axios from 'axios' or add through cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

GET Request

axios.get('/user', {
    params: {
      ID: 1
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

POST Request

axios.post('/user', {
    name: 'Ipseeta',
    id: 1
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Pros

  1. It works on both Nodejs and Browser
  2. Supports Promise API
  3. Can set or cancel a request
  4. Can set a response timeout
  5. Client-side support for protecting against XSRF
  6. Can intercept requests or responses before they are carried out.
  7. Automatic transforms for JSON data

Request

Request is designed to be the simplest way possible to make HTTP calls. It supports HTTPS and follows redirects by default.

Syntax

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error);
  console.log('statusCode:', response && response.statusCode); 
  console.log('body:', body);
});

Pros

API is easy to use

Cons

It is not Promise-based. If you'd like request to return a Promise instead, you can use an alternative interface wrapper for request.

SuperAgent

SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs.

Syntax

SuperAgent has a request object that accepts methods such as GET, POST, PUT, DELETE, and HEAD and then calling .then() (or .end() or await) to send the request.

GET Request

The .query() method accepts objects, which when used with the GET method will form a query-string.

request
   .get('/user')
   .query({ id: 1 })
   .then(res => {

   });

POST Request

request.post('/user')
    .set('Content-Type', 'application/json')
    .send('{"name":"Ipseeta","id":1}')
    .then(callback)
    .catch(errorCallback)

Pros

  1. Nice interface for making HTTP requests.
  2. Works in both Browser and Node.
  3. Multiple functions chaining to send requests.
  4. Supports abortion of requests

Qwest

Qwest is a simple ajax library based on promises and that supports XmlHttpRequest2 special data like ArrayBuffer, Blob and FormData.

Syntax

You can use qwest using npm install qwest or via cdnjs https://cdnjs.com/libraries/qwest

GET request

qwest.get('example.com')
     .then(function(xhr, response) {

     });

POST request

qwest.post('/user', {
        name: 'Ipseeta',
        id: 1
     })
     .then(function(xhr, response) {
     })
     .catch(function(e, xhr, response) {
     });

Pros

It supports request cancellation

var request = qwest.get('example.com')
                   .then(function(xhr, response) {
                       // Won't be called
                   })
                   .catch(function(xhr, response) {
                       // Won't be called either
                   });

request.abort();

Cons

XHR2 is not available on every browser. So if needed, you need to verify XHR version

if(qwest.xhr2) {
    // Actions for XHR2
}
else {
    // Actions for XHR1
}

So, we looked at the most popular JS libraries for AJAX calls in this post. Did I miss anything? Feel free to comment below! πŸ™Œ

Ipseeta Priyadarshini

Software Developer πŸ‘©πŸΌβ€πŸ’» Foodie πŸ˜‹ Explorer πŸ•΅οΈβ€β™€οΈ Dog lover 🐢

Write your comment…

6 comments

Axios, my all time favorite!

Show all replies

Axios is more feature rich than Fetch, like timeouts, interceptor, axios instance, automatic JSON transformation etc.

For smaller projects, I may use Fetch with polyfill

Reply to this…

Share your programming knowledge and learn from the best developers on Hashnode

Get started

Did I miss anything?

I am gonna release version 1.10.0 of cb-fetch pretty soon. Feel free to review it by then.

Sure!

Reply to this…

Hi Ipseeta,

Great article! Axios, Request, and SuperAgent worked for me, as well as Vanilla JS, Fetch API, and jQuery. Is there a unique challenge to setting up Qwest? I couldn't figure that one out. Thanks.

Best, Matt

Reply to this…