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.
| Value | State name | Meaning | Available data |
|---|---|---|---|
| 0 | UNSENT | Object created, open() not called | Nothing |
| 1 | OPENED | open() called, headers can be set | Nothing |
| 2 | HEADERS_RECEIVED | Response status and headers arrived | status, response headers |
| 3 | LOADING | Body is downloading | Partial responseText |
| 4 | DONE | Transfer finished or failed | Full response or error |
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.
| Member | Kind | Purpose |
|---|---|---|
| open(method, url, async) | Method | Initializes the request; async should stay true |
| send(body) | Method | Starts the transfer with an optional body |
| abort() | Method | Cancels an active request |
| responseType | Property | Sets parsing: text, json, blob, arraybuffer, document |
| timeout | Property | Milliseconds before the request fails with timeout |
| withCredentials | Property | Sends cookies on cross-origin requests |
| upload.onprogress | Event | Reports bytes sent during uploads |
| onload, onerror, onloadend | Events | Signal completion, network failure and final cleanup |
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.
| Aspect | XMLHttpRequest | Fetch API |
|---|---|---|
| Programming model | Events and callbacks | Promises, works with await |
| Upload progress | Built in via upload.onprogress | No direct equivalent |
| Download progress | progress events | Readable stream from response.body |
| Cancellation | abort() | AbortController signal |
| Timeout | timeout property | AbortSignal.timeout() |
| HTTP error handling | Check status manually | Check response.ok manually |
| Service worker use | Not available inside workers of that type | Native API in service workers |
| Synchronous mode | Deprecated but possible | Not supported |
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.
| Problem | Cause | Fix |
|---|---|---|
| Page freezes during request | open() called with async set to false | Always use asynchronous mode |
| 404 treated as success | Only onload handled | Check status between 200 and 299 |
| Cross-origin response unreadable | Missing CORS headers on server | Configure Access-Control-Allow-Origin |
| Nested callback chains | Sequential requests with callbacks | Wrap XHR in a Promise or use Fetch |
| Response handled after navigation | Request never aborted | Call abort() on teardown |
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.