AJAX and XMLHttpRequest — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle
You can create web applications that are more responsive and user-friendly by using AJAX and XMLHttpRequest.
Before this article, I mentioned to you that I would start the articles series and I created an Introduction, V8 JavaScript engine, and about the Callbacks. If you lost what I did, check it:
- Introduction — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle
- V8 JavaScript engine — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle
- Callbacks — Understanding JavaScript API Requests and Responses in the Data Fetching lifecycle
In this article series, I’ll not explain the concept of Fetch API or Promises but don’t worry that I’ll explain it in the next article.
AJAX and XMLHttpRequest are important for older Frontend Engineers because they enable the creation of dynamic, interactive web applications that can fetch data from servers without requiring a full page refresh. Prior to the advent of AJAX and XMLHttpRequest, web developers had to rely on clunky and inefficient techniques like iframe-based solutions or full page reloads to update content on web pages and you can create web applications that are more responsive and user-friendly. They can update content on web pages without interrupting the user’s experience or requiring them to wait for a page to reload. Additionally, AJAX and XMLHttpRequest can be used to fetch data in the background, allowing developers to create real-time applications that update automatically as new data becomes available.
What is AJAX?
AJAX is a technique that allows you to update parts of a page dynamically without interrupting the user’s interaction. It’s commonly used in web applications to provide a smoother user experience by making it possible to fetch and display data without requiring a full page refresh. With AJAX, you can make asynchronous requests to a server using JavaScript, and then update the page with the response data. This can be done without interrupting the user’s interaction, allowing them to continue using the page while the request is being processed.
What is XMLHttpRequest?
The XMLHttpRequest (XHR) object is a built-in JavaScript object that provides an easy way to make requests to a server and receive responses. It’s the core technology behind AJAX and is used to fetch data from a server without requiring a page refresh. To use the XMLHttpRequest object, you first need to create an instance of it using the new XMLHttpRequest() constructor. Then, you can use the open() method to specify the request method, URL, and any data to send. Finally, you can use the send() method to send the request to the server.
Making a Request with XMLHttpRequest
In the example below, how to use the XMLHttpRequest object to make a GET request to the Chuck Norris API and handle the response, we’re requesting the Chuck Norris Jokes API to get a random joke.
// Create an XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Set the URL and HTTP method for the request
xhr.open('GET', 'https://api.chucknorris.io/jokes/random');
// Define a callback function to handle the response
xhr.onload = function() {
if (xhr.status === 200) {
// Request was successful
console.log(xhr.responseText);
} else {
// Request failed
console.log(`HTTP error! status: ${xhr.status}`);
}
};
// Define a callback function to handle any errors
xhr.onerror = function () {
console.log("Network error");
};
// Send the request to the server
xhr.send();
Also, you can use the readystatechange event instead of onload, and we’re checking the readyState of the XMLHttpRequest object to make sure that the request has been completed. See the example below.
// Create an XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Define the onreadystatechange event to handle the state change of the request
xhr.onreadystatechange = function () {
// Check if the readyState is 4, which means the request has completed
if (this.readyState === 4) {
// Check if the status code is 200, which means the request was successful
if (this.status === 200) {
// Request was successful
console.log(xhr.responseText);
} else {
// Log an error message to the console if the request was not successful
console.log(`HTTP error! status: ${xhr.status}`);
}
}
};
// Define a callback function to handle any errors
xhr.onerror = function () {
console.log("Network error");
};
// Send the request to the server
xhr.send();
Using Callbacks with XMLHttpRequest
When using XMLHttpRequest in JavaScript, it’s common to use callbacks to handle the response from the server. Callbacks are functions that are passed as arguments to another function and are executed when the function completes its task.
In the example below, I used the same code block above (first example) and added the callback function.
function createRequest(url, callback) {
// Create an XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Set the URL and HTTP method for the request
xhr.open("GET", url);
// Define a callback function to handle the response
xhr.onload = function () {
if (xhr.status === 200) {
// Request was successful and return the callback function
callback(xhr.responseText);
} else {
// Request failed
console.log(`HTTP error! status: ${xhr.status}`);
}
};
// Define a callback function to handle any errors
xhr.onerror = function () {
console.log("Network error");
};
// Send the request to the server
xhr.send();
}
// Call the makeRequest function and pass the parameters URL of the API endpoint we want to fetch and a callback function that logs the response data to the console.
createRequest("https://api.chucknorris.io/jokes/random", (data) => {
console.log(data);
});
XMLHttpRequest and Fetch API
Fetch API has a simpler and more intuitive API compared to XMLHttpRequest, making it easier to use. Fetch API also has built-in support for modern features like Promise-based responses and the ability to cancel requests.
However, XMLHttpRequest has more features and flexibility, including the ability to track progress, set headers, and handle binary data. It also has better support for handling legacy formats like XML and SOAP.
In summary, both AJAX and Fetch API are useful for making asynchronous requests in JavaScript.
Don’t forget preventing Cross-site Scripting (XSS) attacks is a crucial part of web development and should definitely be included as a best practice when using XMLHttpRequest.
However, Fetch API is a newer standard that was introduced in ES6 and provides a simpler and more modern API for making HTTP requests, and Fetch API provides a more modern and streamlined API with better support for modern features like promises and CORS and as commented above I’ll explain it in the next article.
So, If you want to know more about promises, and async/await, please wait for the next article that I’ll publish.
Thank you for reading, I hope this article can somehow have increased your knowledge base about it.