πŸ” AJAX Request & Response Lifecycle
Estimated reading: 4 minutes 48 views

πŸ” 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 onreadystatechange event 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

ValueStateDescription
0UNSENTRequest not initialized
1OPENEDConnection established (open() called)
2HEADERS_RECEIVEDRequest received, headers available
3LOADINGReceiving response body
4DONERequest 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.
  • onreadystatechange tracks 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 readyStateAlways verify readyState === 4 before using response
Ignoring statusCheck xhr.status === 200 to confirm success
Using responseText prematurelyWait until readyState === 4
Misplacing xhr.send()Only call it after setting onreadystatechange

🧠 Best Practices

  • βœ… Always check both readyState and status.
  • βœ… 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 XMLHttpRequest states
  • 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

AJAX – onreadystatechange Event Handling

Or Copy Link

CONTENTS
Scroll to Top