XMLHttpRequest

Also known as: XHR

On this page 7

XMLHttpRequest, commonly abbreviated XHR, is the browser JavaScript interface that lets a script send an HTTP request and receive the response without reloading the page. It is defined in the WHATWG XMLHttpRequest Living Standard and exposed as a constructor on the global object, so new XMLHttpRequest() creates a request object whose state, events and response the script can inspect.

In Browser JavaScript, XHR was the technology that made asynchronous page updates practical in the early 2000s and gave rise to the term Ajax. Despite its name, it transfers any data format, including JSON, plain text, HTML, binary blobs and form data. Modern code usually prefers the Fetch API, yet XHR remains fully supported and is still the only built-in option for some tasks, notably upload progress events.

How an XMLHttpRequest moves through its states

An XHR object follows a fixed lifecycle of five ready states, reported by the readyState property and announced through events. The script calls open() with a method and URL, optionally sets headers with setRequestHeader(), and then calls send() with an optional body.

The table below lists each state, its numeric value and what the script can safely read at that point. Older code checked these values inside an `onreadystatechange` handler; current code typically listens for load, error and timeout instead.

ValueState nameMeaningAvailable data
0UNSENTObject created, open() not calledNothing
1OPENEDopen() called, headers can be setNothing
2HEADERS_RECEIVEDResponse status and headers arrivedstatus, response headers
3LOADINGBody is downloadingPartial responseText
4DONETransfer finished or failedFull response or error
Ready states of an XMLHttpRequest object

Because the request runs asynchronously by default, send() returns immediately and the callbacks run later as tasks scheduled by the event loop. A network failure produces an error event, while an HTTP error such as 404 still reaches state 4 with a `load` event, so the script must inspect status itself.

Key properties, methods and events

The XHR interface is compact, but several members change request behavior in ways that matter in production. The following table groups the most important ones by purpose.

MemberKindPurpose
open(method, url, async)MethodInitializes the request; async should stay true
send(body)MethodStarts the transfer with an optional body
abort()MethodCancels an active request
responseTypePropertySets parsing: text, json, blob, arraybuffer, document
timeoutPropertyMilliseconds before the request fails with timeout
withCredentialsPropertySends cookies on cross-origin requests
upload.onprogressEventReports bytes sent during uploads
onload, onerror, onloadendEventsSignal completion, network failure and final cleanup
Core members of the XMLHttpRequest interface

Setting `responseType` to `json` makes the browser parse the body and expose an object through response, which removes a manual JSON.parse() step. The `withCredentials` flag must be paired with server headers that explicitly permit credentials, otherwise the browser blocks the response.

XMLHttpRequest compared with the Fetch API

The Fetch API replaced XHR as the recommended way to make requests because it returns a Promise and integrates naturally with async/await. The two interfaces still differ in capabilities, as the comparison shows.

AspectXMLHttpRequestFetch API
Programming modelEvents and callbacksPromises, works with await
Upload progressBuilt in via upload.onprogressNo direct equivalent
Download progressprogress eventsReadable stream from response.body
Cancellationabort()AbortController signal
Timeouttimeout propertyAbortSignal.timeout()
HTTP error handlingCheck status manuallyCheck response.ok manually
Service worker useNot available inside workers of that typeNative API in service workers
Synchronous modeDeprecated but possibleNot supported
XMLHttpRequest and Fetch API side by side

Neither interface rejects on HTTP error statuses; both treat a 500 response as a successful transfer. The practical reason to keep XHR today is upload progress reporting, which many file upload widgets still implement with it.

Security rules that govern XHR

Every XHR request is subject to the same-origin policy. A script may read responses from its own origin freely, but cross-origin responses are readable only when the server opts in through Cross-Origin Resource Sharing (CORS) headers such as Access-Control-Allow-Origin.

Requests with custom headers, methods other than GET, HEAD and POST, or non-simple content types trigger a CORS preflight, an automatic OPTIONS request that asks the server for permission first. Browsers also forbid scripts from setting certain headers, including Host, Cookie and Content-Length, because those values must remain under browser control.

Since cookies can accompany requests, XHR endpoints that change state need protection against cross-site request forgery, typically through SameSite cookies or anti-forgery tokens.

Limitations and common mistakes

Most XHR defects in legacy code stem from outdated patterns rather than from the interface itself. The table lists frequent problems with their causes and fixes.

ProblemCauseFix
Page freezes during requestopen() called with async set to falseAlways use asynchronous mode
404 treated as successOnly onload handledCheck status between 200 and 299
Cross-origin response unreadableMissing CORS headers on serverConfigure Access-Control-Allow-Origin
Nested callback chainsSequential requests with callbacksWrap XHR in a Promise or use Fetch
Response handled after navigationRequest never abortedCall abort() on teardown
Typical XMLHttpRequest problems

Synchronous XHR on the main thread is deprecated, and browsers log warnings or ignore settings such as timeout in that mode, because it blocks rendering and user input until the server answers.

The simple explanation

XMLHttpRequest lets a web page talk to a server in the background. The page can ask for new information and get an answer without reloading. You keep reading while the data arrives.

Think of sending a messenger to fetch a document while you stay at your desk. When the messenger returns, the page updates only the part that changed. The key idea is updating part of a page without a full reload. Newer tools do the same job more neatly, but this one still works everywhere.

How it is used in practice

A document management application used by an insurance office lets staff upload scanned claim files of 20 to 200 megabytes. Users complained that large uploads seemed frozen, so they often clicked the button again and created duplicate files.

The frontend developer kept the existing Fetch-based code for ordinary data requests but rewrote the upload routine with XMLHttpRequest. The new code listens to `upload.onprogress`, divides loaded by total and updates a progress bar every few hundred milliseconds. It also sets a timeout of 300,000 milliseconds and exposes a cancel button that calls abort().

After release, staff could see each upload advance and estimate the remaining time. Duplicate uploads largely disappeared, support tickets about frozen screens stopped, and the server no longer stored redundant copies of the same claim files.