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

πŸ§ͺ AJAX – Properties: readyState, status, responseText, responseXML Explained


🧲 Introduction – Why Understand AJAX Response Properties?

When making asynchronous requests using AJAX, knowing how to handle the server’s response properly is critical. Properties like readyState, status, responseText, and responseXML help you track the state of the request, verify success, and read the returned data in various formats.

These properties give you full control over request lifecycle handling, error checking, and dynamic page updates.

🎯 In this guide, you’ll learn:

  • What each of these core properties means
  • How to use them correctly in real projects
  • Code examples showing when and why to use them
  • Common mistakes to avoid

πŸ” What Is readyState in AJAX?

The readyState property represents the current state of the AJAX request. It’s used to monitor the progress of an asynchronous call.

πŸ”’ readyState Values:

ValueDescription
0UNSENT – Request not initialized
1OPENED – Server connection established
2HEADERS_RECEIVED – Request received
3LOADING – Processing request (partial data)
4DONE – Request finished, response is ready βœ…

βœ… Example:

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    console.log("Request complete.");
  }
};

πŸ” What Is status in AJAX?

The status property gives the HTTP status code of the response. It’s used to determine if the request was successful.

πŸ”’ Common HTTP Status Codes:

CodeMeaning
200OK βœ…
201Created
204No Content
400Bad Request
401Unauthorized
403Forbidden
404Not Found ❌
500Server Error ❌

βœ… Example:

if (xhr.readyState === 4 && xhr.status === 200) {
  console.log("Success!");
}

πŸ” What Is responseText in AJAX?

The responseText property contains the raw response data from the server as a string. It’s typically used when the response is plain text, HTML, or JSON.

βœ… Example – Reading Text Response:

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};

To parse JSON:

const data = JSON.parse(xhr.responseText);
console.log(data.username);

πŸ” What Is responseXML in AJAX?

If the server returns XML and the response type is correctly set, responseXML provides a parsed XML document you can query using DOM methods like getElementsByTagName.

βœ… Example:

xhr.onload = function () {
  const xmlDoc = xhr.responseXML;
  const name = xmlDoc.getElementsByTagName("name")[0].textContent;
  console.log("Name:", name);
};

πŸ“Œ Note: The server must return the correct content type (text/xml or application/xml) for this to work.


πŸ§ͺ Full Example – Using All Four Properties

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log("Text:", xhr.responseText);     // raw text
    console.log("XML:", xhr.responseXML);       // parsed XML
  }
};

xhr.send();

βœ… This example checks request completion and logs both the raw response and XML content.


🚨 Common Mistakes to Avoid

❌ Mistakeβœ… Fix
Checking status before readyStateAlways check both readyState === 4 first
Using responseXML on non-XML dataOnly use when server returns XML
Parsing responseText without checking statusAlways verify status === 200
Using responseText for binary filesUse responseType = "blob" instead

πŸ“Œ Summary – Recap & Takeaways

The properties readyState, status, responseText, and responseXML are the core building blocks for handling AJAX responses effectively. They allow you to track request progress, verify success, and extract data from the response.

πŸ” Key Takeaways:

  • readyState tracks request progress (0 to 4)
  • status helps confirm success (e.g., 200 OK)
  • responseText returns raw response as a string
  • responseXML provides parsed XML from the response

βš™οΈ Next Steps:

  • Try building a small XML parser using responseXML
  • Use responseText with JSON.parse() for JSON APIs
  • Learn how to use responseType for binary or blob responses

❓ FAQs – AJAX Properties


❓ What does readyState === 4 mean?
βœ… It means the request has completed, and the response is fully received and available for processing.


❓ Why is my responseXML returning null?
βœ… This happens if the server doesn’t return Content-Type: text/xml or if the response isn’t valid XML.


❓ Can I use responseText with JSON?
βœ… Yes. You can parse it using JSON.parse(xhr.responseText).


❓ Is it necessary to check status if readyState === 4?
βœ… Yes. You must check both to confirm the request was successful:

if (xhr.readyState === 4 && xhr.status === 200)

❓ What’s the difference between responseText and responseXML?
βœ… responseText gives the full raw response as a string; responseXML parses XML into a DOM structure.


Share Now :

Leave a Reply

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

Share

AJAX – Properties: readyState, status, responseText, responseXML

Or Copy Link

CONTENTS
Scroll to Top