XHR v/s fetch v/s ajax v/s Axios for API requests

Dev Sharma
ADGVIT
Published in
5 min readMar 1, 2021
Web API, different types of Request and Responses
Web APIs (Image Source)

Introduction

Requesting resources from an API is a pretty common and almost vital feature needed for building modern applications. Whether you’ve built your own API or you’re using a third-party API, you need a way to make your requests without slowing down your application.

If you’re a developer you must be familiar with the term API if not, let me explain. API stands for an application programming interface. It is a set of subroutine definitions, data structures, object classes, protocols, and tools for building software and applications.

To put it in simple words, API is some kind of interface that has a set of functions that allow programmers to access specific features or data of an application, operating system, or other services.

Programmers use API technology to write applications that provide useful services to your site’s visitors, such as access to remote database content and your website services. Some external APIs make it possible to display content from third-party services like Google Maps, Twitter, and Facebook, while others allow you to accept online payments.

Why APIs?

API services
API Services (Image Source)

The advantages of using an Application Programming Interface, or API, in Web development, are based on an API’s ability to interact with Web pages.

They allow the users to access remote password-protected databases making information sharing easier and more secure, they allow content to be embedded from any site or application more easily. This guarantees more fluid information delivery and an integrated user experience.

How do we use them?

API’s work on the CRUD principle. CRUD stands for Create, Read, Update, and Delete. But put more simply, in regards to its use in RESTful APIs, CRUD is the standardized use of HTTP Action Verbs. This means that if you want to create a new record you should be using “POST.” If you are trying to read a record, you should be using “GET.” To update a record utilizing “PUT” or “PATCH.” And to delete a record, using “DELETE.”

The most commonly used API technologies are XMLHttpRequest, Ajax, FetchAPI, and Axios. Let us see how each of these works.

XMLHttpRequest

XMLHttpRequest method is the Godfather of all API technologies. It has been in existence ever since the first Internet Explorer was launched in the year 2000.

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.
Even though the name suggests otherwise it can handle all types of data.

To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response body and the HTTP status of the result.

function reqListener () {console.log(this.responseText);}var oReq = new XMLHtttpRequest();oReq.addEventListener(“load”, reqListener);oReq.open(“GET”, “http://www.example.org/example.txt");oReq.send();

A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that is set on the XMLHttpRequest.open() method. If this argument is true or not specified, the XMLHttpRequest is processed asynchronously, otherwise, the process is handled synchronously.

FetchAPI

fetch API (Image Source)

fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

  • Created on xhr with built-in promises.
  • Compact syntax than xhr.

The below-given code snippet showcases the syntax of a simple fetch() request.

fetch(url) // Call the fetch function passing the url of the API as a parameter.then(function() {// Your code for handling the data you get from the API}).catch(function() {// This is where you run code if the server returns any errors});

Working with fetch():

  • The Fetch API allows you to asynchronously request a resource.
  • Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json(). These methods also resolve into the actual data.
  • Use the status and statusText properties of the Response object to get the status and status text of the response.
  • use the catch() method or try…catch statement to handle a failure request.

jQuery AJAX

“Ajax” stands for Asynchronous Javascript And XML, jQuery provides a condensed format to make XMLHTTPRequest. AJAX is the art of exchanging data with a server and updating parts of a web page — without reloading the whole page.

  • Cross-browser support
  • Simple methods to use
  • Define the type of request

jQuery ajax base syntax:

$.ajax({name:value, name:value, … })

$.ajax makes the call to ajax, then the methods are called in place of a name and the callbacks as value, as the example given below.

jQuery ajax Example:

$(“button”).click(function(){$.ajax({url: “demo_test.txt”,type: “get”,success: function(result){result = JSON.parse(result)console.log(result);}});});

$(“button”).click(function()

The onclick listener is added to the button tag.

$.ajax({

url: “demo_url”,

type: “get”,

success: function(result){

The ajax function uses xmlHTTPRequest to make a get request to the specified URL: “demo_url”, and the response is stored in the result.

success: function(result){

result = JSON.parse(result)

console.log(result);

}});

The response is received in a JSON format here so we first need to convert it into a javascript object using JSON.parse() function, now we can use the response obtained from the request as a regular javascript object, it can be logged into the console to test.

Axios

axios logo
AXIOS (Image Source)

Axios is a popular promise-based 3rd party library client that has an easy-to-use API and can be used in both browser and node.js, it supports the promise API, also supports the feature to cancel requests and automatically transform JSON data.

  • has a way to set a response timeout
  • has a way to cancel a request
  • performs automatic JSON data transformation
  • supports upload progress
const getData = () =>axios.get(‘http://www.example.org/example.txt').then(function(response) {//your code for handling API dataconsole.log(response)}).catch(function(err) {//your code for handling API errorconsole.log(err);});document.getElementById(‘get-button’).addEventListener(‘click’, getData());

The Axios request is being stored in a const getData function which can be activated on an event listener.

Conclusion

When it comes to ease of use and syntax XHR may not be the favored choice due to explicitly adding promises which makes it unnecessarily complex, this is easily overcome by using the fetch API which comes with promises built-in and hence an easier syntax. Both the jQuery ajax and Axios are similar to the fetch API, the difference is the added features that they bring.

Connect me: GitHub, LinkedIn

— A collab with Divesh Arora (GitHub, LinkedIn)

--

--