ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

AJAX & Fetch API Tutorial• 6 min read

Legacy XMLHttpRequest (XHR) & ReadyStates

open(), send(), onreadystatechange, and the 5 readyState phases

Before the modern fetch() API, all asynchronous requests were orchestrated via the XMLHttpRequest (XHR) object.

The 5 readyState Phases of XHR

0: UNSENT: Client has been created, open() not called yet.

1: OPENED: open() has been invoked.

2: HEADERS_RECEIVED: send() called, response headers and status are available.

3: LOADING: Response body is being downloaded (responseText contains partial data).

4: DONE: The transfer operation is 100% complete.

Classic XMLHttpRequest Implementation
const xhr = new XMLHttpRequest();

// Configure GET request
xhr.open("GET", "https://api.example.com/data", true);

// Listen to state transitions
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) { // DONE
    if (xhr.status === 200) {
      const data = JSON.parse(xhr.responseText);
      console.log("Success:", data);
    } else {
      console.error("HTTP Error:", xhr.status);
    }
  }
};

// Send the request
xhr.send();
XHR requires tracking readyState === 4 and status === 200 manually.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

In XMLHttpRequest, which `readyState` value indicates that the request operation is fully completed?