HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

AJAX - The Server Response

Once a request is sent, the server processes it and sends back data. The XMLHttpRequest object provides several properties to access this response data and metadata like headers.


Response Header Inspector

Click the button below to fetch a file and inspect the HTTP Response Headers sent back by the server:

Click the button to see headers...

Response Properties

The two main properties used to retrieve data from the server are:

  • responseText: Returns the server response as a JavaScript string.
  • responseXML: Returns the server response as an XML DOM object (for XML data).

Using responseText

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
  }
};

The readyState Event

The onreadystatechange property defines a function to be executed every time the status of the XMLHttpRequest object changes.

Modern Alternative: You can also use the onload event, which only triggers when the request is successfully completed (Equivalent to readyState 4).

Response Status

Before processing data, you should always check the HTTP status code:

  • 200: "OK" (Request succeeded)
  • 403: "Forbidden" (No access)
  • 404: "Not Found" (File doesn't exist)

Accessing Response Headers

Headers provide extra information about the server response, such as content type, date, or server software.

getAllResponseHeaders()

Returns all the header information as a single string.

let headers = xhttp.getAllResponseHeaders();

getResponseHeader()

Returns a specific piece of header information.

let contentType = xhttp.getResponseHeader("Content-type");

Key Points to Remember

  • responseText is for normal text and JSON.
  • responseXML is for structured XML data.
  • Check status == 200 before using data.
  • Headers contain metadata about the response.
  • Use onload for cleaner, modern AJAX code.