π AJAX β onreadystatechange Event Handling: Complete Guide with Examples
π§² Introduction β What Is onreadystatechange in AJAX?
When using AJAX via the XMLHttpRequest object, you need a way to monitor the progress of the request. Thatβs where the onreadystatechange event handler comes into play. It allows you to execute specific actions as the request progresses through different statesβfrom initializing to completed.
The most common use case? Executing a callback when the server response is ready (i.e., readyState = 4 and status = 200).
π― In this guide, youβll learn:
- What the
onreadystatechangeevent is and how it works - The five readyState values and their meanings
- How to handle different states of an AJAX request
- Practical code examples and best practices
π¦ What Is the onreadystatechange Event?
The onreadystatechange is an event handler property of the XMLHttpRequest object. It gets triggered every time the readyState of the request changes. You can use it to determine when the response is ready to be processed.
π AJAX readyState Values Explained
| Value | State | Description |
|---|---|---|
| 0 | UNSENT | Request not initialized |
| 1 | OPENED | Connection established (open() called) |
| 2 | HEADERS_RECEIVED | Request received, headers available |
| 3 | LOADING | Receiving response body |
| 4 | DONE | Request complete and response ready |
β
We usually wait for readyState === 4 before handling the response.
π§ Basic AJAX Example Using onreadystatechange
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log("User:", data.name);
}
};
xhr.send();
π Explanation:
xhr.open(...)initializes the request.xhr.send()sends the request.onreadystatechangetracks progress.- Inside the function, we check:
xhr.readyState === 4: request completed.xhr.status === 200: successful response.
π§ͺ Example β Handle All Ready States (Debugging Tool)
xhr.onreadystatechange = function () {
console.log("ReadyState:", xhr.readyState);
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Success:", xhr.responseText);
} else {
console.error("Request failed. Status:", xhr.status);
}
}
};
β Useful for debugging the full lifecycle of a request.
π Using Named Function with onreadystatechange
Instead of using an anonymous function:
function handleStateChange() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Response:", xhr.responseText);
}
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "info.txt", true);
xhr.onreadystatechange = handleStateChange;
xhr.send();
β Improves reusability and clarity.
π Use Case β Load Content Without Page Reload
Letβs update part of a webpage (like a div) using onreadystatechange:
<button onclick="loadContent()">Load Info</button>
<div id="content"></div>
function loadContent() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "info.html", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("content").innerHTML = xhr.responseText;
}
};
xhr.send();
}
β This enables partial content updates without reloading the whole page.
β οΈ Common Mistakes and Fixes
| β Mistake | β Fix |
|---|---|
Not checking readyState | Always verify readyState === 4 before using response |
Ignoring status | Check xhr.status === 200 to confirm success |
Using responseText prematurely | Wait until readyState === 4 |
Misplacing xhr.send() | Only call it after setting onreadystatechange |
π§ Best Practices
- β
Always check both
readyStateandstatus. - β Use named callbacks for maintainability.
- β Add error handling for non-200 status codes.
- β Avoid doing heavy DOM updates until data is fully received.
π Summary β Recap & Takeaways
The onreadystatechange event is a key feature of the XMLHttpRequest object. It ensures that your JavaScript code waits for the server response before actingβavoiding errors and incomplete data usage.
π Key Takeaways:
- It monitors request lifecycle via readyState values (0 to 4)
- Only proceed when
readyState === 4 && status === 200 - Works well with JSON, HTML, or plain text responses
- Essential for controlling AJAX response behavior
βοΈ Next Steps:
- Practice with multiple
XMLHttpRequeststates - Add fallback UI for error handling
- Transition to
fetch()and compare callback mechanisms
β FAQs β AJAX onreadystatechange Event
β Is onreadystatechange the only way to detect response completion?
β
No. You can also use xhr.onload, but onreadystatechange provides more granular control over different states.
β Why is my response empty even when status is 200?
β
Check that readyState === 4 before accessing xhr.responseText.
β Can I use onreadystatechange with POST requests?
β
Yes. It works for all HTTP methods, including POST, PUT, DELETE, etc.
β How do I handle errors like 404 or 500?
β
Check xhr.status inside the readyState === 4 block and provide fallbacks or error messages.
β Is onreadystatechange still used in modern development?
β
Yes, especially for legacy code. However, modern apps often use fetch() and Promises for cleaner syntax.
Share Now :
