Everything You Need to Know About JavaScript AJAX

Jamie Oppel

Published:

Have you ever left an application like Gmail open and seen something update in real time? I think it’s pretty neat to see that happen. Imagine having to refresh the page every time you got a new email to see it. Wouldn’t that be so annoying?

man uses javascript ajax in code

Well, you can thank technologies like AJAX for preventing such a cumbersome experience from existing in your day-to-day life on the internet.

Download Now: An Introduction to JavaScript  [Free Guide]

In this article, you will learn about JavaScript AJAX, how to use it, and an example of it in action. It primarily will enable you to read and send data to and from web servers, and you can use it to update a web page without reloading anything. Pretty nifty, right?

What is AJAX in JavaScript?

AJAX stands for Asynchronous Javascript And XML. As previously mentioned, it enables you to send or receive data from a server and update information on a page without needing to reload it. Asynchronous in this context means being able to update information at a later date. You're already used to this, considering that many things on the internet are asynchronous, such as chat messengers or email.

An object called XMLHttpRequest (or just “XHR” for short) is used to accomplish all of this. Despite its name, any type of data can be worked with, not just XML. This includes things like JSON, HTML, and text files as well.

To leverage the power of AJAX, you will need to make an HTTP request and then handle the server response. If everything is successful, you can update content based on the response.

How to Use AJAX in JavaScript

Earlier, I said you need to make an HTTP request to use AJAX. Well, to create an HTTP request, you will first need to create an XMLHttpRequest object. It’s no different than building an instance of any other object in JavaScript. See below for an example and the syntax for doing so.

> const xhr = new XMLHttpRequest(); // variableName = new XMLHttpRequest();

After that, you will need to define a function that dictates what happens once a response from the server is ready. This function can then be specified by setting the onreadystatechange property of the XHR object to the name of the function to be used.

> function handleResponse() {

        // Codemfor what to do after the response is receive goes here

}

Xhr.onereadystatechange = handleResponse;

Of course, to actually receive a response, you need to request one first. To do this, the open() and send() methods of the XHR object will be used and may look something like the following. 

> xhr.open(“GET”, “https://www.somewebsite.com/file.txt”, true);

xhr.send();

As you may have noticed, there are three parameters in the open() method. The first is the HTTP request method. You can use methods other than a simple GET here, such as POST, which would send data rather than receive it. Just keep the method entirely in uppercase letters since that’s the standard.

The second parameter is the URL you’re sending the request to. By default, you cannot call third-party URLs. This can be changed via CORS if needed.

The third parameter is optional but simply says whether or not the request is asynchronous and defaults to true. It’s typically recommended that you leave the third parameter on “true” since attempting to have a synchronous request instead of an asynchronous one can lead to unexpected behavior and a poor user experience.

Okay, great! That covers the HTTP request part, but now you need to go back to the earlier function and define how the response is handled. To do that, you need to know what kind of responses you can get back. In the earlier example, I simply called this function handleResponse().

To know if the request has been received successfully, you will want to check the state of the request and see if it’s done. Check out the following code for how to do this.

> if (xhr.readyState === XMLHttpRequest.DONE) {

        //The request finished and the response what received successfully

} else {

        //The response isn’t ready or hasn’t been initialized

}

If the readyState is done, we can move to the next step of checking the HTTP status codes of the HTTP response. If it’s a 200 status code, you can continue. If it’s something else, that may indicate a problem with the request or even a problem with the internal server.

> if (xhr.status === 200) {

        // Everything is okay!

} else {

        // There was a problem with the request or even a problem with the internal server, not good!

}

Finally, once everything is good to go, you can use the data that the server sent. You also have two choices for accessing it, either as a string of text using the xhr.responseText() method, or the xhr.responseXML() method, which would return the response as an XMLDocument object.

JavaScript Ajax Example

To help solidify these concepts, I will help walk you through a simple example. You will request a basic HTML document using a simple button and some JavaScript that sends off the request. Below is some code and its related webpage. Go ahead and read through the code, and see if you can figure out what will happen before I explain it.

Also, note that the “test.html” file is in the same directory. Whether you’re requesting JSON, XML, or anything else, it should be in the same directory to access it.

Button for the above HTML file

So, what’s going on here? To start, we have a button on the page (and nothing else), simply called the xhrButton.

Button that sends request

Attached to that button is an event listener that says, “Once I’m clicked, run the requestData() function.”

Event listener for the xhr button

This function then instantiates a new XHR object that creates and sends a GET request asking for the “test.html” file, and execution is passed to the alertContents() function.

requestData function that sends off an HTTP request

Finally, the alertContents function checks for an OK response and returns the response text. This is thrown into an alert() function in this example.

requestData function that sends off an HTTP request

And that’s it! Since the “test.html” file was requested in this example, the contents of “test.html” are what is thrown into the alert() function, which is shown below.

Contents of test.html

It’s also worth mentioning that if you run this code from your local filesystem, you might run into a CORS policy error such as this.

CORS policy error

If that happens to you, don’t fret! The solution is to host all of this on a web server. That can still be set up locally using VS Code or other methods. Check out this video for more help with that particular issue.

Getting Started

That covers the essentials of using AJAX in JavaScript. This powerful technology allows for efficient server communication, making it possible to get data and make changes to a website dynamically. By leveraging JavaScript Ajax, developers can create more interactive and responsive web applications.

New Call-to-action

Topics: Javascript

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about one of the world's most popular programming languages.