J

JavaScript Handbook

Clean • Professional

AJAX Response in JavaScript

1 minute

AJAX Response

When an AJAX request is sent to a server, the server responds with data. The XMLHttpRequest object provides properties and methods to access this response.

Server Response Properties

responseText

  • Returns the response from the server as a string.
  • Use this when the server sends plain text, HTML, or JSON (parse JSON if needed).

Example:

const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if(xhttp.readyState === 4 && xhttp.status === 200) {
    document.getElementById("demo").innerHTML = xhttp.responseText;
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

responseXML

  • Returns the server response as an XML DOM object.
  • Useful when the server sends XML data.
  • Can be navigated using standard DOM methods like getElementsByTagName().

Example:

const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if(xhttp.readyState === 4 && xhttp.status === 200) {
    const xmlDoc = xhttp.responseXML;
    const artists = xmlDoc.getElementsByTagName("ARTIST");

    let txt = "";
    for(let i = 0; i < artists.length; i++) {
      txt += artists[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
  }
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();

Server Response Methods

getResponseHeader(headerName)

  • Returns the value of a specific HTTP response header.
  • Useful for checking metadata like Content-Type, Last-Modified, etc.

Example:

const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
  document.getElementById("demo").innerHTML =
    this.getResponseHeader("Last-Modified");
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

getAllResponseHeaders()

  • Returns all HTTP response headers as a single string.
  • Headers are separated by CRLF (\\r\\n).

Example:

const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
  document.getElementById("demo").innerHTML =
    this.getAllResponseHeaders();
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

 

Article 0 of 0