XMLHttpRequest
XMLHttpRequest — old school, how does it work, examples
The XMLHttpRequest
(XHR) API is the first and fundamental built-in method for making HTTP requests in JavaScript, appearing in the early 2000s alongside Ajax technology. It allows browser applications to make asynchronous (non-blocking) and synchronous (blocking) HTTP requests without refreshing the entire page.
XHR implements network communication at a low level using the browser's internal network stack and provides detailed control over requests, including:
However, the XHR API also has some limitations:
Now let's look at a simple example of how to make a GET request with XHR and receive a JSON response:
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = JSON.parse(xhr.responseText);
console.log("Response data:", response);
} catch (e) {
console.error("Failed to parse JSON:", e);
}
} else {
console.error("Request failed with status:", xhr.status);
}
}
};
xhr.onerror = function() {
console.error("Network error occurred");
};
xhr.send();
Explanations:
open()
method sets the request type and URLonreadystatechange
tracks different request states via readyState
status
contains the server's response status code (200-299 range indicates success)responseText
contains the data received from the server as textsend()
executes the requestConclusion:
Fetch API
for a cleaner, Promise-based API