JavaScript AJAX (Asynchronous JavaScript and XML) is a technique that gives the ability to send and receive data asynchronously from a web server. AJAX allows you to create rich, responsive user interfaces. It makes it easy to update data on the page without having to reload the entire page. It makes your application more responsive and user-friendly.

I’m going to show you two different ways to make an Ajax request.

 

1. Using XMLHttpRequest object:

XMLHttpRequest (also known as XHR) object. This object is built into most browsers (even in Internet Explorer) and allows you to send requests and receive responses without having to reload the page.

Get request:

// Create the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
// Initialize the request
xhr.open("GET", 'https://jsonplaceholder.typicode.com/users');
// Send the request
xhr.send();
// Fired once the request completes successfully 
xhr.onload = function(e) {
    // Check if the request was a success
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
    	// Get and convert the responseText into JSON
    	var response = JSON.parse(xhr.responseText);
    	console.log(response);
    }
}

 

Post request:

// Create the XMLHttpRequest object.
const xhr = new XMLHttpRequest();
// Initialize the request
xhr.open("POST", 'https://jsonplaceholder.typicode.com/users', true);
// Set content type
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
// Send the request with data to post
xhr.send(
    JSON.stringify({
        name : "Jon Doe",
        username : "jon-doe",
        email : 'jon-doe@unknown.com'
    })
);
// Fired once the request completes successfully 
xhr.onload = function(e) {
    // Check if the request was a success
    if (this.readyState === XMLHttpRequest.DONE && this.status === 201) {
    	// Get and convert the responseText into JSON
    	var response = JSON.parse(xhr.responseText);
    	console.log(response);
    }
}

 

2. Using fetch() method:

fetch() method is the newer, easier, and best method to make Ajax requests. The fetch() method returns a promise that can be used to handle the response data. Though, this method won’t work on old browsers like Internet Explorer.

Get request:

// Create and Send the request
var fetch_status;
fetch('https://jsonplaceholder.typicode.com/userssss', {
    method: "GET",
    headers: {
        "Content-type": "application/json;charset=UTF-8"
    }
})
.then(function (response) {
    // Save the response status in a variable to use later.
    fetch_status = response.status;
    // Handle success
    // eg. Convert the response to JSON and return
    return response.json();
}) 
.then(function (json) {
    // Check if the response were success
    if (fetch_status == 200) {
        // Use the converted JSON
        console.log(json);
    }
})
.catch(function (error){
    // Catch errors
    console.log(error);
}); 

 

Post request:

// Create and Send the request
var fetch_status;
fetch('https://jsonplaceholder.typicode.com/users', {
    method: "POST",
    // Set the headers
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    // Set the post data
    body: JSON.stringify({
        name : "Jon Doe",
        username : "jon-doe",
        email : 'jon-doe@unknown.com'
    })
})
.then(function (response) {
    // Save the response status in a variable to use later.
    fetch_status = response.status;
    // Handle success
    // eg. Convert the response to JSON and return
    return response.json();
}) 
.then(function (json) {
    // Check if the response were success
    if (fetch_status == 201) {
        // Use the converted JSON
        console.log(json);
    }
})
.catch(function (error){
    // Catch errors
    console.log(error);
}); 

 

In the above snippets, once the fetch() method’s request is successfully executed on the server, the first then() method converts the response data info a JavaScript object. Then, in the second then() method, we can use the object to do whatever we want to do. If there were any errors encountered in the chain, it would pass into the catch() method.