AJAX – The XMLHttpRequest Object
15 April 2025 | Category: JavaScript
The XMLHttpRequest
object is one of the earliest ways to send AJAX requests in JavaScript — to communicate with a web server without reloading the page.
What is XMLHttpRequest
?
The XMLHttpRequest
(XHR) object lets JavaScript send HTTP requests to servers and handle their responses asynchronously.
You can:
- GET data from a server (read)
- POST data to a server (send)
- Load JSON, text, or even XML files dynamically
✅ Basic Workflow of XMLHttpRequest
- Create an XHR object
- Set up the request (method + URL)
- Send the request
- Handle the response when it’s ready
🚀 Example: Make a GET Request
<button onclick="loadUser()">Load User</button>
<p id="result"></p>
<script>
function loadUser() {
// 1. Create the XMLHttpRequest object
const xhr = new XMLHttpRequest();
// 2. Set up the request
xhr.open("GET", "https://jsonplaceholder.typicode.com/users/1", true);
// 3. Set up a function to handle the response
xhr.onload = function () {
if (xhr.status === 200) {
const user = JSON.parse(xhr.responseText);
document.getElementById("result").innerText = `Name: ${user.name}`;
} else {
document.getElementById("result").innerText = "Error loading user.";
}
};
// 4. Send the request
xhr.send();
}
</script>
✅ Output: When the button is clicked, it fetches and displays the user’s name.
🧪 Explanation of Properties and Methods
Property/Method | Description |
---|---|
xhr.open(method, url) | Prepares the request |
xhr.send() | Sends the request to the server |
xhr.responseText | Holds the response data (string) |
xhr.status | HTTP status code (200 = OK) |
xhr.onload | Event triggered when response is ready |
xhr.onreadystatechange | Older way to track state changes |
xhr.readyState | Tracks progress (0 to 4) |
📘 readyState Values
Value | Meaning |
---|---|
0 | Request not initialized |
1 | Server connection established |
2 | Request received |
3 | Processing request |
4 | Request finished and response ready ✅ |
🚀 Example: POST Request using XHR
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function () {
console.log("Response:", xhr.responseText);
};
const data = JSON.stringify({
title: "Hello",
body: "This is a post",
userId: 1
});
xhr.send(data);
This sends JSON data to the server.
🆚 XMLHttpRequest vs Fetch API
Feature | XMLHttpRequest | Fetch API |
---|---|---|
Syntax | Verbose | Clean & Promise-based |
Error Handling | Manual | .catch() supported |
Modern Usage | ❌ Outdated | ✅ Recommended |
✅ Summary
XMLHttpRequest
is the traditional way to make AJAX requests.- Still useful to understand, especially for legacy code.
- For modern apps,
fetch()
is easier and cleaner.