J

JavaScript Handbook

Clean • Professional

XMLHttpRequest (XHR) in JavaScript

2 minute

XMLHttpRequest (XHR)

The XMLHttpRequest (XHR) object is a built-in browser API that allows JavaScript to communicate with a server asynchronously, forming the foundation of traditional AJAX. XHR enables partial page updates without reloading the entire page.

Supported in all modern browsers: Chrome, Firefox, Edge, Safari, IE, and Opera.

Creating an XMLHttpRequest Object

const xhttp = new XMLHttpRequest();
  • This creates a new XHR object.
  • Modern browsers have it built-in; no extra library required.

Sending a Request

Use open() to initialize the request and send() to send it:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();
  • GET or POST can be used.
  • Optional parameters: async (true or false), username, and password.

Callback Functions

Using onload

onload executes when the request completes successfully:

xhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Multiple Callback Functions for Different Tasks

Allows reusing one XHR function with different callback functions.

loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() { cFunction(this); }
  xhttp.open("GET", url);
  xhttp.send();
}

function myFunction1(xhttp) { /* action */ }
function myFunction2(xhttp) { /* action */ }

Using onreadystatechange

  • onreadystatechange triggers every time readyState changes.
  • The response is ready when readyState = 4 and status = 200.
function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt");
  xhttp.send();
}

XHR Object Properties

PropertyDescription
onloadFunction executed when the request completes successfully
onreadystatechangeFunction executed when readyState changes
readyStateStatus of the request (0–4)
responseTextResponse as a string (text, JSON, HTML)
responseXMLResponse as an XML document
statusHTTP status code (e.g., 200, 403, 404)
statusTextStatus message (e.g., "OK", "Forbidden", "Not Found")

readyState values:

ValueStateDescription
0UNSENTRequest not initialized
1OPENEDConnection established
2HEADERS_RECEIVEDRequest received
3LOADINGProcessing request
4DONERequest finished; response ready

XHR Object Methods

MethodDescription
open(method, url, async, user, psw)Initializes the request
send()Sends the request; optionally send string for POST
setRequestHeader(header, value)Sets HTTP headers
abort()Cancels the current request
getResponseHeader(header)Returns value of a specific header
getAllResponseHeaders()Returns all response headers

Access Across Domains

  • For security reasons, browsers block AJAX requests across domains without CORS.
  • Both the page and requested file must be on the same server, unless the server allows cross-origin requests.

Advantages & Limitations

Advantages:

  • Works in all browsers, modern and older.
  • Supports partial page updates.
  • Handles multiple data formats (JSON, XML, text, HTML).

Limitations:

  • Verbose and complex syntax compared to Fetch API.
  • Requires manual handling of JSON/XML parsing.
  • Error handling is less intuitive.

Modern Alternative: Fetch API

fetch("ajax_info.txt")
  .then(res => res.text())
  .then(data => console.log(data))
  .catch(err => console.error(err));

 

Article 0 of 0