Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Beyond Fetch

XMLHttpRequest and Legacy AJAX

Understand XMLHttpRequest: readyState, load and progress events, timeouts and uploads, how to convert XHR code to fetch, and why JSONP is obsolete.

Before fetch() existed, there was XMLHttpRequest, usually shortened to XHR. It is the API that gave AJAX its name: Microsoft built the first version for Outlook Web Access in the late 1990s, other browsers copied it, and by the mid-2000s it powered web apps that felt like desktop software. The name is misleading, because XHR is not limited to XML. It transfers text, JSON, HTML and binary data just as well.

You should learn XHR for two reasons. First, you will meet it in older codebases, jQuery plugins, analytics snippets and libraries such as early versions of Axios, and you need to read and migrate that code. Second, XHR can still do two things fetch() cannot do in a standard way: report upload progress and run a request with a simple synchronous-style timeout property. For everything else, fetch() is the better tool.

The sandbox has no server, so live examples request data: URLs, which are URLs that carry their content inside themselves. The XHR code is identical to what you would write for a real address such as https://api.example.com/users.

The shape of an XHR request

An XHR request is an object you create, configure, send and then listen to. Nothing is promise-based: you attach event handlers and the browser calls them later.

JavaScript
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/users/7");   // method, url (nothing is sent yet)
xhr.setRequestHeader("Accept", "application/json");
xhr.responseType = "json";                            // let the browser parse the body

xhr.addEventListener("load", () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(xhr.response);                        // already an object
  } else {
    console.log("HTTP error", xhr.status);
  }
});
xhr.addEventListener("error", () => console.log("Network error"));

xhr.send();                                           // the request starts here

Notice what is different from fetch(). open() only configures the request; send() actually starts it. HTTP errors do not trigger the error event, which is reserved for network-level failures, so you must check xhr.status inside load. That part is the same idea as checking response.ok, and the fetch error handling lesson explains why it matters.

readyState and events

Every XHR object has a readyState number that moves through five values as the request proceeds:

Value Name Meaning
0 UNSENT The object exists, open() has not been called
1 OPENED open() was called, you can set headers and call send()
2 HEADERS_RECEIVED Status and headers have arrived
3 LOADING The body is arriving (partial data may be available)
4 DONE The operation finished, successfully or not

Old code listened to a single onreadystatechange handler and tested readyState === 4. Modern XHR offers specific events that are much easier to use: loadstart, progress, load (finished successfully), error, abort, timeout and loadend (always fires last, whatever the outcome).

stateDiagram-v2
  [*] --> UNSENT
  UNSENT --> OPENED: open called
  OPENED --> HEADERS_RECEIVED: send called, headers arrive
  HEADERS_RECEIVED --> LOADING: body arrives
  LOADING --> DONE: last byte
  DONE --> [*]

The readyState values in the order a normal request visits them.

Run the next example to watch the sequence. It logs every readystatechange together with the named events. The exact number of intermediate steps can vary between browsers, but you will always see the state reach 4 followed by load and loadend.

JS Watching readyState and events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reading the response

XHR gives you several ways to read the answer. The responseType property decides what xhr.response contains:

  • "" or "text": a string (also available as xhr.responseText).
  • "json": the body already parsed. If the body is not valid JSON, xhr.response is null, which hides the error; with "text" plus your own JSON.parse() you get a proper exception.
  • "blob" and "arraybuffer": binary data such as images and files.
  • "document": a parsed HTML or XML document.

You must set responseType after open() and before send(). Also, xhr.responseText throws an error if responseType is anything other than text, a common surprise during migrations.

Progress and uploads

XHR reports progress in both directions. xhr.onprogress follows the download, and xhr.upload.onprogress follows the data you send. Both give a ProgressEvent with loaded, total and lengthComputable. Only trust total when lengthComputable is true; a server that streams without a Content-Length header gives no total.

JavaScript
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/videos");

xhr.upload.addEventListener("progress", (event) => {
  if (event.lengthComputable) {
    bar.value = (event.loaded / event.total) * 100;
  }
});

xhr.addEventListener("load", () => {
  status.textContent = xhr.status === 201 ? "Uploaded!" : "Upload failed";
});

xhr.send(new FormData(form));

This is the one job where many projects still reach for XHR. The forms lesson uses it for a progress bar. (Download progress is possible with fetch() by reading response.body as a stream, covered in the streaming lesson.)

Aborting and timeouts

xhr.abort() cancels a running request and fires the abort event. Setting xhr.timeout to a number of milliseconds makes the browser cancel the request itself and fire the timeout event, which is simpler than the fetch() equivalent of an AbortSignal.timeout(). A timed-out or aborted request will not fire load, so handle each event you care about, or put shared cleanup in loadend.

Synchronous XHR: never use it

Passing false as the third argument to open() makes the request synchronous: the whole page freezes until the server answers. If the server is slow, the user cannot scroll, click or even close the tab smoothly. Browsers print warnings about it, the specification deprecated it for the main thread, and some features are disabled in this mode. There is no good reason to use it in new code.

Converting XHR code to fetch

Most XHR code translates directly. Here is the same request in both styles, running side by side on the same data: URL, so you can verify that the result is identical.

XHR and fetch compared

This mapping table covers the common cases:

XHR fetch
xhr.open("POST", url) fetch(url, { method: "POST" })
xhr.setRequestHeader(name, value) headers: { [name]: value }
xhr.send(body) body: body
xhr.status in load response.status / response.ok
xhr.responseType = "json" and xhr.response await response.json()
xhr.addEventListener("error", ...) the promise rejects (use catch)
xhr.timeout = 5000 signal: AbortSignal.timeout(5000)
xhr.abort() controller.abort()
xhr.withCredentials = true credentials: "include"
xhr.upload.onprogress no standard equivalent (keep XHR)
xhr.getResponseHeader("X") response.headers.get("X")

Two behavioral differences deserve attention while migrating. Cookies: XHR sends cookies for same-origin requests and, with withCredentials, for cross-origin ones, just like fetch() does with its credentials option. Errors: with XHR you handle error, abort and timeout events separately, while fetch() rejects for all of them (an abort rejects with a DOMException named AbortError and a timeout with TimeoutError).

A useful trick when migrating a large codebase is to wrap XHR in a small promise function first, so callers can use await immediately, and then replace the inside with fetch() later:

JavaScript
function request(method, url, body) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.addEventListener("load", () => {
      if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.responseText);
      else reject(new Error("HTTP " + xhr.status));
    });
    xhr.addEventListener("error", () => reject(new Error("Network error")));
    xhr.addEventListener("timeout", () => reject(new Error("Timed out")));
    xhr.send(body);
  });
}

JSONP: a hack from the past

Before browsers had CORS, a page could not read responses from another origin with XHR. The workaround was JSONP ("JSON with padding"). Browsers never block <script> tags from loading code on other domains, so a page added a script tag that pointed to the API and named a global function to call:

JavaScript
// Read-only: do not do this in new code
function handleWeather(data) {
  console.log(data.temp);
}
const script = document.createElement("script");
script.src = "https://api.example.com/weather?city=Oslo&callback=handleWeather";
document.head.append(script);
// The server replies with executable code:  handleWeather({"temp": 4});

It worked, but it was dangerous. The response is code that runs with full access to your page, so a compromised or malicious API can steal everything: cookies not marked HttpOnly, tokens, form contents. It supports only GET, offers no error handling (a failed script load tells you nothing useful) and requires a global function name. CORS replaced it more than a decade ago and every browser supports it, so the right answer to a JSONP API today is to ask the provider for CORS headers, or to call it through your own server. If you maintain old code with JSONP calls, plan to replace them. Our security lesson explains why running third-party code is the root problem.

When to still use XHR

Choose fetch() by default. Choose XHR when you need upload progress without a library, when you must support a very old browser that lacks fetch() (rare today), or when you are maintaining code where a rewrite is not worth the risk. Everything else, including streaming downloads, request cancellation, service worker integration and Request/Response objects, is fetch() territory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In XHR, which call actually starts the request?

    open() only configures the request. Nothing is sent until you call send().
  2. 2. A server answers an XHR request with status 500. Which event fires?

    error is for network-level failures. An HTTP error status still completes the request, so load fires and you inspect the status.
  3. 3. What is readyState 4?

    The values are 0 UNSENT, 1 OPENED, 2 HEADERS_RECEIVED, 3 LOADING and 4 DONE.
  4. 4. Which fetch option replaces xhr.timeout = 5000?

    fetch() has no timeout option; you pass a signal that aborts after the given time.
  5. 5. Why is JSONP considered unsafe?

    A JSONP response is code, not data. Whoever controls the API controls what runs on your page.

Summary

  • XHR creates an object, calls open(), optionally sets headers and responseType, then send(); results arrive through events.
  • readyState goes UNSENT, OPENED, HEADERS_RECEIVED, LOADING, DONE; use load, error, abort, timeout and loadend instead of onreadystatechange.
  • HTTP error statuses still fire load: check xhr.status.
  • xhr.upload.onprogress is the practical way to show upload progress; synchronous XHR must never be used.
  • Converting to fetch() is mostly mechanical: AbortSignal.timeout() replaces timeout, controller.abort() replaces abort(), response.json() replaces responseType = "json".
  • JSONP loads executable code from another site and is obsolete; use CORS or a server-side proxy.

Next: Streaming and Real-Time APIs goes beyond one request and one response.