AJAX – XMLHttpRequest Tutorial
15 April 2025 | Category: JavaScript
What is XMLHttpRequest
?
XMLHttpRequest
(also known as XHR) is a JavaScript object that allows the browser to communicate with a server in the background without reloading the entire page.
It is a core part of AJAX (Asynchronous JavaScript and XML).
đź§ With XHR, you can fetch data (GET) or send data (POST) without refreshing your webpage.
âś… When to Use XMLHttpRequest
?
- Loading user data from an API
- Submitting a form without reloading
- Live search suggestions
- Chat apps, notifications, dynamic content loading
đź§° Basic Syntax
const xhr = new XMLHttpRequest(); // 1. Create the object
xhr.open("GET", "url", true); // 2. Configure the request
xhr.onload = function () { // 3. Define what to do when response arrives
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(); // 4. Send the request
💡 XHR Lifecycle – readyState
values
Value | Description |
---|---|
0 | Request not initialized |
1 | Server connection established |
2 | Request received |
3 | Processing request |
4 | Request finished and response is ready âś… |
🚀 Example 1: GET Request (Fetch Data from Server)
<button onclick="loadData()">Get User</button>
<p id="output"></p>
<script>
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/users/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
const user = JSON.parse(xhr.responseText);
document.getElementById("output").innerText = `Name: ${user.name}`;
}
};
xhr.send();
}
</script>
âś… This fetches data from an API and updates the HTML without reloading the page.
🚀 Example 2: POST Request (Send Data to Server)
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.status === 201) {
console.log("Response:", xhr.responseText);
}
};
const data = JSON.stringify({
title: "New Post",
body: "This is some sample data",
userId: 1
});
xhr.send(data);
âś… This sends JSON data to the server.
đź“‘ Key XHR Properties
Property | Description |
---|---|
xhr.responseText | Text response from server |
xhr.status | HTTP status code (200 = OK) |
xhr.readyState | Current state of request |
xhr.onreadystatechange | Runs at each change in readyState |
xhr.onload | Runs when request is complete (readyState 4) |
🆚 XHR vs Fetch API
Feature | XMLHttpRequest | fetch() (Modern) |
---|---|---|
Syntax | Verbose | Cleaner (promise-based) |
Error Handling | Manual | Easier with .catch() |
Support | All browsers | All modern browsers |
Usage Today | Legacy code | Recommended for new code |
📝 Summary
XMLHttpRequest
is a core tool for making AJAX requests.- Use
.open()
to prepare the request and.send()
to send it. - Use
.onload
or.onreadystatechange
to handle the response. - Mostly replaced by the Fetch API, but still important to know.