AJAX and XMLHttpRequest in JavaScript (Live Playground)
AJAX (Asynchronous JavaScript and XML) is a technique that enables web applications to send and receive data from a server without refreshing the entire page. XMLHttpRequest is a built-in JavaScript object that facilitates AJAX by making HTTP requests and processing the responses. In this tutorial, we will learn how to use XMLHttpRequest to make asynchronous API requests.
Creating an XMLHttpRequest
To create an XMLHttpRequest object, simply instantiate a new object using the XMLHttpRequest constructor:
Example:
const xhr = new XMLHttpRequest();
Configuring the Request
Use the open() method to specify the request type, URL, and whether the request should be asynchronous:
Example:
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
Handling the Response
The onreadystatechange event handler is triggered when the readyState property of the XMLHttpRequest object changes. Check if the request is complete (readyState equals 4) and if the response status is successful (status 200).
Example:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
Sending the Request
After configuring the request and handling the response, use the send() method to send the request:
Example:
xhr.send();
Conclusion
AJAX and XMLHttpRequest provide a way to make asynchronous API requests and update your web applications without refreshing the entire page. This improves user experience and allows for smoother interactions with your website.