WittCode💻

JavaScript XMLHttpRequest and AJAX

By

Learn about XHR (XMLHttpRequest) and its relationship with AJAX. Also compare XMLHttpRequest vs fetch().

Table of Contents 📖

What is an XMLHttpRequest?

An XMLHttpRequest, or XHR, is an API used for communication between a client and server, such as making a GET request to a URL to retrieve data. Despite having XML in its name, an XHR can be used to retrieve JSON, HTML, plain text, and XML. Using XHR is powerful because it enables parts of the web page to be updated without doing a full page refresh.

XMLHttpRequest and AJAX

XHR is used as part of the Asynchronous JavaScript and XML (AJAX) technique. AJAX is essentially a model to make web applications quicker as they update the user interface without reloading the entire page.

Creating an XMLHttpRequest

To create an XMLHttpRequest we create an instance of the XMLHttpRequest class. The XMLHttpRequest class is built into browsers so there is no need to download any external software/library.

const xhttp = new XMLHttpRequest();

Initializing an XMLHttpRequest

Now we need to initialize our request. In other words, we need to tell our XMLHttpRequest where we want to send it. This can be done with the method open().

xhttp.open();

This method takes a few arguments. The first is the HTTP request method the request is using such as GET or POST. Here, we want our XMLHttpRequest to perform a GET request. GET requests are used to retrieve data from a provided URL.

xhttp.open('GET');

Our XHR now knows the request method to use, but it doesn't know where to send the request to. We can specify this in the second argument by providing a URL. Here, we are going to send a GET request to an API called JSONPlaceholder that is typically used for testing.

xhttp.open('GET', 'https://jsonplaceholder.typicode.com/users');

This code above sends a GET request to the provided URL. This URL will provide us a list of users in JSON format.

Sending an XMLHttpRequest

Our XMLHttpRequest is now set up, we just have to send it off. This is done with the method send().

xhttp.send();

We can check the status of our XHR by using the browser network tools.

Image

We can see that this XHR has a status code of 200 meaning it was successful. We can also see the request method we used along with the request URL that we supplied to the open() method.

Handling XHR Response

The request URL we sent the XHR to returns a JSON array of users. We can also view this in our chrome dev tools by clicking on the XHR and then going to response.

Image

To handle this response with our XHR, we need to use the property onreadystatechange.

xhttp.onreadystatechange

The onreadystatechange property is called whenever the readyState attribute of the XHR changes. The readyState property can have the values 0-4, where each number represents the state of the XMLHttpRequest.

Image

Based on the graph above, we need to listen for when the ready state has a value of 4.


xhttp.onreadystatechange = () => {

    if (xhttp.readyState === 4) {
        console.log('Data retrieved!');
    }

}
    

If the readyState property has a value of 4, then the XHR operation completed. We can further check the XHR operation by checking the status code.

xhttp.onreadystatechange = () => {

    if (xhttp.readyState === 4 && xhttp.status === 200) {
        console.log('Data retrieved successfully!');
    }

}
    

The status property of the XHR is a read only property that contains the HTTP status of the response. If the status code is 200, then the response was ok and we are good to go.

Accessing the HTTP Response Data

To access the actual response data, we use the response property of the XHR object.

xhttp.onreadystatechange = () => {

    if (xhttp.readyState === 4 && xhttp.status === 200) {
        alert(xhttp.response);
    }

}

The response property returns a DOMString, ArrayBuffer, Document, JavaScript object, or Blob depending on the value of the responseType property. The responseType property defines the response type. We can also check the type of response data from the response headers.

Image

XHR and AJAX Demonstration

Lets demonstrate the power of XHR and Ajax by retrieving a random user from an API on a button click and then displaying that user without reloading the whole page. To do this, lets create an HTML file and place