XMLHttpRequest in AJAX XHR is an important AJAX topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem XMLHttpRequest in AJAX XHR solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of XMLHttpRequest in AJAX XHR should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
XMLHttpRequest in AJAX XHR should be studied as a practical AJAX lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the ajax > xmlhttprequest page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
XMLHttpRequest (XHR) is a built-in browser object that enables JavaScript to make HTTP requests to a server without reloading the page. It was originally developed by Microsoft for Internet Explorer 5 and later standardized by the W3C. Despite its name, XHR can transfer any type of data - not just XML.
// 1. Create the XHR object
const xhr = new XMLHttpRequest();
// 2. Configure: open(method, url, async)
// method: 'GET', 'POST', 'PUT', 'DELETE', etc.
// url: the endpoint to call
// async: true (default) = non-blocking
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
// 3. Set up the response handler
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
const post = JSON.parse(xhr.responseText);
console.log('Title:', post.title);
} else {
console.error('Request failed with status:', xhr.status);
}
};
// 4. Handle network errors
xhr.onerror = function () {
console.error('Network error occurred');
};
// 5. Send the request
xhr.send();
The readyState property tracks the state of the XHR request through its lifecycle. It changes from 0 to 4 as the request progresses.
| Value | State | Description |
|---|---|---|
| 0 | UNSENT | Object created, open() not called yet. |
| 1 | OPENED | open() called, request not sent yet. |
| 2 | HEADERS_RECEIVED | send() called, response headers received. |
| 3 | LOADING | Response body is being downloaded. |
| 4 | DONE | Request complete (success or failure). |
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/users', true);
// onreadystatechange fires every time readyState changes
xhr.onreadystatechange = function () {
console.log('readyState:', xhr.readyState);
if (xhr.readyState === XMLHttpRequest.DONE) { // === 4
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log('Data:', data);
} else {
console.error('Error:', xhr.status, xhr.statusText);
}
}
};
xhr.send();
You can set a timeout (in milliseconds) to automatically cancel a request that takes too long. The abort() method lets you cancel a request programmatically.
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/slow-endpoint', true);
// Cancel request if it takes more than 5 seconds
xhr.timeout = 5000;
xhr.ontimeout = function () {
console.warn('Request timed out after 5 seconds');
};
// Send cookies and auth headers with cross-origin requests
xhr.withCredentials = true;
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
// Manually cancel the request (e.g., user navigates away)
document.getElementById('cancel-btn').addEventListener('click', () => {
xhr.abort();
console.log('Request aborted');
});
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
// Track download progress
xhr.onprogress = function (event) {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
console.log(`Download: ${percent}%`);
}
};
// Track upload progress
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
document.getElementById('progress-bar').style.width = percent + '%';
}
};
xhr.onload = () => console.log('Upload complete:', xhr.status);
xhr.onerror = () => console.error('Upload failed');
const formData = new FormData(document.getElementById('upload-form'));
xhr.send(formData);
When studying XMLHttpRequest in AJAX XHR, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In AJAX, XMLHttpRequest in AJAX XHR becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
const state = { topic: "XMLHttpRequest in AJAX XHR", ready: true };
if (state.ready) {
console.log(state.topic + ": render or run the normal path");
}
const response = null;
const message = response?.message ?? "XMLHttpRequest in AJAX XHR: show a clear fallback";
console.log(message);
Memorizing XMLHttpRequest in AJAX XHR without the situation where it is useful.
Connect XMLHttpRequest in AJAX XHR to a concrete AJAX task.
Testing XMLHttpRequest in AJAX XHR only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to XMLHttpRequest in AJAX XHR.
Memorizing XMLHttpRequest in AJAX XHR without the situation where it is useful.
Connect XMLHttpRequest in AJAX XHR to a concrete AJAX task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in AJAX, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.