Introduction
There are many options for different ways to call Ajax in JavaScript that can greatly improve user experiences, such as sending data to the server, checking usernames, creating autocomplete forms, voting and ratings, creating chat rooms, and so on.
This article covers information about the latest list of different options for making AJAX calls. To keep it simple, let's focus on what they are, there are some pros and cons to each option.
1. XHR
XMLHttpRequest is an object (a native component in most other browsers, an ActiveX object in Microsoft Internet Explorer) that allows a web page to make a request to a server and receive a response without reloading the entire page. The user continues on the same page as if the page had not been reloaded and, more importantly, does not see or notice the processing - that is, at least by default, does not see a new page load.
Using the XMLHttpRequest object allows the developer to modify a page already loaded in the browser with data from the server, without having to re-request the entire page from the server.
Making a GET request using XHR
const Http = new XMLHttpRequest();
const url='http://yourdomain.com/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}Making a send request using XHR
var xhr = new XMLHttpRequest();
xhr.open("POST", '/submit', 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=Ketan&id=1");2. Fetch API
The Fetch API is a new alternative to XMLHttpRequest for retrieving resources from a server. Unlike XMLHttpRequest, it has a more powerful feature set and more meaningful names. Fetch is also flexible and easy to use due to its syntax and structure. However, what sets it apart from other AJAX HTTP libraries is that it is supported by all modern web browsers. Fetch follows a request-response approach where Fetch makes a request and returns a promise that resolves to a Response object.
Benefits of using Fetch API
- It is flexible and easy to use.
- Callback Hell is avoided by Promises
- Supported by all modern browsers
- Follows a request-response approach
Disadvantages of using Fetch API
- Does not send cookies by default.
- CORS is disabled by default.
Making a GET request in the Fetch API
fetch('https://www.yourdomain.com', {
method: 'get'
})
.then(response => response.json())
.then(jsonData => console.log(jsonData))
.catch(err => {
//error block
}Making a POST request in the Fetch API
var url = 'https://www.yourdomain.com/updateProfile';
var data = {username: 'courseya'};
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));3. jQuery
jQuery is a client-side programming language that you can use to create cool and amazing web applications. It's free, yet powerful, relatively easy to set up and learn, and has several plugins and extensions to do just about anything you can imagine or think of. You can get started quickly and you won't be able to outgrow it later when you really get the hang of it.
Advantages of using jQuery
- The biggest advantage of jQuery is its simplicity.
- It is also incredibly flexible because jQuery allows users to add plugins.
- It is also a very quick solution to your problems. While there may be «better» solutions, jQuery and its developer work as a team to ensure that you can implement jQuery quickly and effectively, which saves you money.
- Open source software means rapid growth and freedom for developers to provide the best possible service without red tape.
Disadvantages of using jQuery
- Also, frequent updates mean that community members are also unlikely to offer solutions.
- There are also many different versions of jQuery available now, and some are less compatible than others.
- Sometimes jQuery is slower in some cases compared to CSS. At that time its simplicity becomes a curse because it is not for client-side interactions.
Making a GET request in jQuery
$.ajax({
url: '/users',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(`Error ${error}`);
}
});Making a POST request in Jquery
$.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}`);
}
});4. Axios
Axios is one of many promise-based HTTP clients that work both in the browser and in the node.js environment. It basically provides a single API to deal with XMLHttpRequest and the node HTTP interface. Apart from that, it connects requests using a polyfill for the new ES6 syntax.
Benefits of using Axios
- Promise Out-of-the-Box Support
- Client-side support for protection against XSRF
- Can record requests or responses before they are carried out.
- Automatic conversion for JSON data
- Supports Promise API
- Can adjust or cancel a request
- Can adjust response time
- Works on both Nodejs and the browser
Making a GET request in Axios
axios.get('/get-user', {
params: {
ID: 1
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});Making a POST request in Axios
axios.post('/user', {
name: 'Sanjeev',
id: 1
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});5. Request
The Request library is one of the simplest ways to make HTTP calls. The structure and syntax are very similar to how requests are handled in Node.js. Currently, the project has 18k stars on GitHub and is worth mentioning because it is one of the most popular HTTP libraries available.
Syntax
var request = require('request');
request('http://www.yourdomain.com', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});6. SuperAgent
SuperAgent is a lightweight and advanced AJAX library that focuses more on readability and flexibility. Unlike other libraries available, SuperAgent has a gentle learning curve. SuperAgent has a request object that accepts methods such as GET, POST, PUT, DELETE, and HEAD.
SuperAgent Benefits
- It has a plugin-based environment and ecosystem where extensions can be built and developed for additional or additional functionality.
- Easily adjustable
- Nice interface for HTTP requests.
- Multiple chaining functions for sending requests.
- It should support upload and download progress.
- It has support for fragmented transport encryption.
- Old-style calls are supported.
- Numerous plugins are available for many common features.
Make a get request
request
.get('/user')
.query({ id: 1 })
.then(res => {
});Make a post request
request.post('/user')
.set('Content-Type', 'application/json')
.send('{"name":"Ipseeta","id":1}')
.then(callback)
.catch(errorCallback)Result
The choice will depend on your project, its scale, and its intended audience and adoption. There is no right or wrong choice. If you choose the wrong library for the wrong requirements, this question may be answered. Choose the right tool for the job.









