JavaScript

How to make an AJAX call in JavaScript?

JavaScript is a high-level programming language where code is executed line by line and is called synchronous execution of code. The disadvantage of synchronous execution is that the next lines of code have to wait for the complete execution of the current line of code. The answer to this problem is asynchronous execution, in asynchronous a statement or a line does not have to wait for the previous code to completely execute rather they can execute in parallel. To achieve asynchronous execution of code, AJAX comes into play.

In this post, we will see what AJAX is and how to make an AJAX call in JavaScript with the help of an example.

What Is AJAX?

AJAX became popular in 2005 when google put it up in their google suggest and it stands for asynchronous JavaScript and XML. XML stands for Extensible Markup Language that is used to encrypt messages which can be read by humans and machines. XML is similar to HTML, but it lets you build and customize your own tags. The function of AJAX is to transmit requests to a server and then receive data from that server in an asynchronous fashion.

The advantage of AJAX is that it performs its function without the need of refreshing the whole page. For example, when you type something to search for in the google search bar, with every key press the search bar makes AJAX calls and the user receives suggestions without actually refreshing the page.

It should be noted that the AJAX communicates with the server using the XMLHttpRequest object, JavaScript/DOM to make requests, and XML as a data transmission mechanism.

AJAX is triggered with an event and then performs its functionality by first creating an XMLHttpRequest object and then sending the HttpRequest to the server where the HttpRequest is processed and a response is generated which is then sent back to the browser with some data. The browser processes the returned data and updates the page content using JavaScript.

Now that we know what AJAX is and how to make an AJAX call using JavaScript.

AJAX Call using JavaScript

In this example, we will first initialize the XMLHttpRequest object which is used to communicate with the server or to put it simply, make an AJAX call. The XMLHttpRequest has many built-in methods that we can use to manipulate or play with the server by sending, interrupting responses, and receiving data from the server. We will connect to a free fake API to test our AJAX call. The link of the API we are going to use is given below:

https://jsonplaceholder.typicode.com/

The complete code to make an AJAX call is given below:

functionmyFunc() {

// Initializing XMLHttpRequest object
varxhttp = newXMLHttpRequest();

// Establish connection with fake API
varurl = 'https://jsonplaceholder.typicode.com/todos/1';
// get api from url
xhttp.open("GET", url, true);

// When the request is successful the below function will execute
xhttp.onreadystatechange = function () {
// if request is complete and succesful
if (this.readyState == 4&&this.status == 200) {
console.log(this.responseText);
        }
    }
// Send Request
xhttp.send();
}
// call myFunc function
myFunc();

In the above code, first, we initialized a function with the name of myFunc(), and inside this function, we created an XMLHttpRequest object. Next, we establish the connection with an API using a URL. To get the API we use the xhttp.open() method and pass the HTTP method GET and the URL. The get method is used when we are getting some data from a server and the POST method is used when we are writing or updating data on the server.

Now when the request will finish executing and if it’s successful, the onreadystatechange event will execute where we are using a condition that if the request is complete and the request was successful, console log the data. The status code 200 is used which means ok. The 400 status code means error and the 300 status code means redirecting to some page. The next step is to send the request using the send() method.

In the end, we call the myFunc() function and we will see the following output in the console log:

The status code seen in the developer tools is 200 which means ok:

Conclusion

AJAX stands for asynchronous JavaScript and XML where XML is used to encrypt messages that are made in readable format for humans and machines except that XML lets you customize your own tags. AJAX allows you to transmit data to the server without having to refresh the entire page. It performs its operation asynchronously hence improving speed as the code does not have to wait for the previous code to complete its execution. In JavaScript, the XMLHttpRequest object is used to make an AJAX call.

In this post, first, we discussed what AJAX is and then went on to discuss how to make an AJAX call in javaScript using the XMLHttpRequest object.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.