How to make a simple AJAX call in Vanilla JavaScript

by SlideFactory

One of the most common questions we get asked by new developers is the how to make a simple AJAX call in vanilla JavaScript. AJAX, or Asynchronous JavaScript and XML, is a technique used to enable web pages to communicate with a server asynchronously. This means not needing to refresh the entire page when something changes. This allows for the creation of more dynamic and responsive web applications. It also allows you to ensure only the necessary data is transmitted to and from the server.

The XMLHttpRequest object

To make a simple AJAX call, you first need to create an XMLHttpRequest object. This object is used to send and receive data from the server. The following code creates an XMLHttpRequest object and assigns it to the variable “request”:

var request = new XMLHttpRequest();

Specify the request endpoint

Next, you need to specify the URL of the server. This is the url that you want to communicate with. You will also need specify the type of request (GET or POST) you will use. The following code sets the URL to “http://example.com” and the request type to “GET”:

request.open("GET", "http://example.com");

Send the Request

After setting the URL and request type, you can then send the request to the server using the send() method. The following code sends the request:

request.send();

Handle the response

To handle the response from the server, you can use the onreadystatechange event of the XMLHttpRequest object. This event is triggered whenever the ready state of the object changes. It allows you to check the status of the response and access the data returned by the server. The following code shows how to use the onreadystatechange event to handle the response from the server:

request.onreadystatechange = function() {
  if (request.readyState == XMLHttpRequest.DONE) {
    // Check the status of the response
    if (request.status == 200) {
      // Access the data returned by the server
      var data = request.responseText;
      // Do something with the data
    } else {
      // Handle error
    }
  }
};

In this code, the onreadystatechange event is used to check the status of the response from the server. If the response is successful (i.e. the status is 200), then the data returned by the server is accessed. Otherwise, an error is handled.

Wrapping it up

Overall, the question of how to make a simple AJAX call in Vanilla JavaScript call is a fairly straightforward process. It involves creating an XMLHttpRequest object, setting the URL and request type, sending the request, and handling the response. AJAX is a great way to create more dynamic and responsive web applications. By learning these simple techniques, you can create better applications and use data more effectively. If you’re a beginner, w3schools is a great place to start.

Share this article:

You might also like: