How to Make an AJAX Call without jQuery

Introduction

In the current web development landscape, AJAX is the backbone of modern web applications, which allows us to seamlessly exchange data between the client and server without requiring a page reload. While libraries like jQuery have made AJAX calls simpler to do, it's still important to understand how to make AJAX calls without relying on these libraries.

This Byte will guide you through the process of making an AJAX call using pure JavaScript.

Understanding AJAX

AJAX is a web development technique that allows a web page to communicate with a server, update its content, and do so without causing a disruptive full page reload. It's done with JavaScript and XML (though these days JSON is more commonly used) to send and receive data.

The real magic happens when JavaScript and the XMLHttpRequest object are used to interchange data asynchronously with a server. This is where the 'A' in AJAX comes from - Asynchronous. This means that it is possible to send data to, and retrieve data from, a server in the background, allowing the user to interact with the page as normal while the AJAX request is being processed.

How to Make an AJAX Call without jQuery

To make an AJAX call without jQuery, we use the XMLHttpRequest object, a built-in browser object that allows us to make HTTP requests to external resources. It's the key object that gives AJAX its power, as it allows for the asynchronous exchange of data between client and server. Let's dive a bit deeper into how the XMLHttpRequest object works.

Overview

XMLHttpRequest is a built-in browser object that can be used to make HTTP requests in JavaScript to exchange data between the web browser and the server. Despite the name, XMLHttpRequest can be used to retrieve any type of data, not just XML. Somewhat surprisingly, XMLHttpRequest was originally supposed to support protocols other than HTTP (including file and ftp), however, most major browsers don't actually support it.

The XMLHttpRequest object works by first creating an instance of the object, setting up a request, and then sending the request. Once the request is sent, a function is then defined to handle the response data from the server.

Here's a quick overview of what an AJAX call with XMLHttpRequest might look like:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200)
    console.log(xhr.responseText);
}
xhr.send();

In the following sections, we'll break down each of these steps to understand how they work in detail.

Creating an Instance of XMLHttpRequest

The first step in making an AJAX call without jQuery is to create an instance of the XMLHttpRequest object. This object provides methods for transferring data between a client and a server.

let xhr = new XMLHttpRequest();

Setting up the Request

Once we've created an instance of XMLHttpRequest, the next step is to set up our request. This is done using the open() method, which takes three parameters: the type of request (GET, POST, etc.), the URL to which the request is sent, and whether the request should be made asynchronously.

xhr.open('GET', 'https://api.example.com/data', true);

Here, we're making a GET request to 'https://api.example.com/data' asynchronously. The third parameter is set to true to make the request asynchronous. If you set it to false, the request will be synchronous and the execution of the JavaScript will pause until the server responds.

Handling the Response

Before the request can actually be sent, we need to tell XMLHttpRequest how to handle the response from the server. This is done using the onreadystatechange event listener, which is triggered every time the readyState property of the XMLHttpRequest object changes.

The readyState property holds the status of the XMLHttpRequest. When readyState is 4, that means the request is complete and the response is ready.

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
}

In this code, we're checking if readyState is 4 and status is 200. If both conditions are true, we log the response text to the console.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

The status property returns the status-number of a request. 200 means "OK". Other common status-codes include 404 ("Not Found") and 500 ("Server Error").

Sending the Request

Now that our request is all set up, we can finally send it using the send() method:

xhr.send();

This line of code sends the request to the server. If you're making a POST request, you would pass your data as a parameter to the send() method.

Error Handling in AJAX without jQuery

As with any programming task (especially network requests), errors can and will occur. You'll need to handle these errors to avoid issues with your app and keep it user-friendly. In the case of AJAX, we can handle errors using the onerror event handler of the XMLHttpRequest object.

var xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.github.com/users/stackabuse', true);

xhr.onerror = function() {
    console.log('Request Error...');
}

xhr.send();

In the above code, we've attached a function to the onerror event handler. This function will be called if an error occurs with the AJAX request. In this case, we're simply logging a message to console, but in a real-world application, you can handle it in a few different ways:

  • Inform the user about the error
  • Try the request again
  • Fail silently

Of course, there are many other ways to handle these errors, but those listed above are just a few.

Note: The onerror event handler won't be triggered for HTTP errors like a 404 or 500 status. It's only triggered for network-level errors, such as the request being blocked by CORS policy or the user losing internet connection.

For handling HTTP errors, you can check the status code of the response in the onload event handler, like so:

var xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.github.com/users/stackabuse', true);

xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 400) {
        // Success!
        console.log(xhr.responseText);
    } else {
        // We reached our target server, but it returned an error
        console.log('Server Error!');
    }
};

xhr.onerror = function() {
    // There was a connection error of some sort
    console.log('Connection Error!');
};

xhr.send();

In this snippet, we're checking if the status code of the response is in the range of 200-399, which represents successful HTTP responses. If it's not in this range, we're logging a server error message.

Conclusion

And that's it! In this Byte we started with understanding what AJAX is, then we went into detail about the XMLHttpRequest object, and how to create an instance of it. We also covered setting up, sending, and handling the response of an AJAX request. And finally, we learned how to handle errors that might occur during the process.

While libraries like jQuery can make AJAX calls easier, it's important to know how to do it without relying on external libraries. It not only helps you understand how things work under the hood but also equips you with the knowledge to handle situations where using a library might not be the best option.

Last Updated: September 22nd, 2023
Was this helpful?
Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms