XMLHttpRequest Object

Estimated study time: 14 minutes.

The XMLHttpRequest (XHR) object is the browser API that makes AJAX possible. It lets JavaScript open a connection to a server, send a request, and handle the response — all without leaving the current page.

Creating an XHR Object

let xhr = new XMLHttpRequest();
xhr.open("GET", "students.xml", true);
xhr.send();

Key Methods

  • open(method, url, async) — configures the request without sending it.
  • send(body) — fires off the request, optionally with data.
  • setRequestHeader(name, value) — sets a header before sending.
  • abort() — cancels an in-progress request.

Key Properties

  • readyState — tracks the request's lifecycle (0 to 4).
  • status — the HTTP status code of the response (e.g. 200, 404).
  • responseText — the raw response as a string.
  • responseXML — the response parsed as an XML document.

Listening for the Response

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseXML);
  }
};
💡 Tip: readyState === 4 means the request is complete. Always check status === 200 too, since a completed request can still have failed.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with the Data Analytics Course at Uncodemy.

Explore XML Course →