XMLHttpRequest is an API that provides client functionality for transferring data between a client and a server. It provides an easy way to retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just a part of the page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
XMLHttpRequest was originally designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now being standardized at the WHATWG. Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).
Syntax
var myRequest = new XMLHttpRequest();
For details about how to use XMLHttpRequest, see Using XMLHttpRequest.
Properties
This interface also inherits properties of XMLHttpRequestEventTarget and of EventTarget.
XMLHttpRequest.onreadystatechange- An
EventHandlerthat is called whenever thereadyStateattribute changes. The callback is called from the user interface thread.
Warning: This should not be used with synchronous requests and must not be used from native code. XMLHttpRequest.readyStateRead only- Returns an
unsigned short, the state of the request:Value State Description 0UNSENTClient has been created. open()not called yet.1OPENEDopen()has been called.2HEADERS_RECEIVEDsend()has been called, and headers and status are available.3LOADINGDownloading; responseTextholds partial data.4DONEThe operation is complete. XMLHttpRequest.responseRead only- Returns an
ArrayBuffer,Blob,Document, JavaScript object, or aDOMString, depending of the value ofXMLHttpRequest.responseType. that contains the response entity body. This isnullif the request is not complete or was not successful. XMLHttpRequest.responseTextRead only- Returns a
DOMStringthat contains the response to the request as text, ornullif the request was unsuccessful or has not yet been sent. XMLHttpRequest.responseType- Is an enumerated value that defines the response type. It can have the following values:
Value Data type of responseproperty""DOMString(this is the default value)"arraybuffer"ArrayBuffer"blob"Blob"document"Document"json"JavaScript object, parsed from a JSON string returned by the server "text"DOMString"moz-blob"Used by Firefox to allow retrieving partial Blobdata from progress events. This lets your progress event handler start processing data while it's still being received."moz-chunked-text"Similar to
"text", but is streaming. This means that the value inresponseis only available during dispatch of the"progress"event and only contains the data received since the last"progress"event.When
responseis accessed during a"progress"event it contains a string with the data. Otherwise it returnsnull.This mode currently only works in Firefox.
"moz-chunked-arraybuffer"Similar to
"arraybuffer", but is streaming. This means that the value inresponseis only available during dispatch of the"progress"event and only contains the data received since the last"progress"event.When
responseis accessed during a"progress"event it contains a string with the data. Otherwise it returnsnull.This mode currently only works in Firefox.
Note: Starting with Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8), as well as WebKit build 528, these browsers no longer let you use the
responseTypeattribute when performing synchronous requests. Attempting to do so throws anNS_ERROR_DOM_INVALID_ACCESS_ERRexception. This change has been proposed to the W3C for standardization. XMLHttpRequest.responseURLRead only- Returns the serialized URL of the response or the empty string if the URL is null. This value will be the final URL obtained after any redirects.
XMLHttpRequest.responseXMLRead only Not available to workers- Returns a
Documentcontaining the response to the request, ornullif the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. The response is parsed as if it were atext/xmlstream. When theresponseTypeis set to"document"and the request has been made asynchronously, the response is parsed as atext/htmlstream.responseXMLis null fordata:URLs.Note: If the server doesn't apply thetext/xmlContent-Type header, you can useoverrideMimeType()to forceXMLHttpRequestto parse it as XML anyway. XMLHttpRequest.statusRead only- Returns an
unsigned shortwith the status of the response of the request. This is the HTTP result code (for example,statusis 200 for a successful request). XMLHttpRequest.statusTextRead only- Returns a
DOMStringcontaining the response string returned by the HTTP server. UnlikeXMLHTTPRequest.status, this includes the entire text of the response message ("200 OK", for example). XMLHttpRequest.timeout- Is an
unsigned longrepresenting the number of milliseconds a request can take before automatically being terminated. A value of 0 (which is the default) means there is no timeout.Note: You may not use a timeout for synchronous requests with an owning window. - Using a timeout with an asynchronous request
XMLHttpRequestEventTarget.ontimeout- Is an
EventHandlerthat is called whenever the request times out. XMLHttpRequest.uploadRead only- Is an
XMLHttpRequestUpload, representing the upload process. It is an opaque object, but being anXMLHttpRequestEventTargetevent listeners can be set on it to track its process. XMLHttpRequest.withCredentials- Is a
Booleanthat indicates whether or not cross-siteAccess-Controlrequests should be made using credentials such as cookies or authorization headers. - In addition, this flag is also used to indicate when cookies are to be ignored in the response.
- The default is
false.Note: This never affects same-site requests.Note: Starting with Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8), Gecko no longer lets you use thewithCredentialsattribute when performing synchronous requests. Attempting to do so throws anNS_ERROR_DOM_INVALID_ACCESS_ERRexception.Note:XmlHttpRequestresponses from a different domain cannot set cookie values for their own domain unlesswithCredentialsis set totruebefore making the request, regardless ofAccess-Control-header values.
Non-standard properties
| Attribute | Type | Description |
|---|---|---|
channel Read only |
nsIChannel |
The channel used by the object when performing the request. This is null if the channel hasn't been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. Requires elevated privileges to access. |
mozAnon Read only |
boolean |
If true, the request will be sent without cookie and authentication headers. |
mozSystem Read only |
boolean |
If true, the same origin policy will not be enforced on the request. |
mozBackgroundRequest |
boolean |
This method is not available from Web content. It requires elevated privileges to access. Indicates whether or not the object represents a background service request. If In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead. Note: This property must be set before calling
open(). |
mozResponseArrayBuffer Obsolete since Gecko 6 Read only |
ArrayBuffer |
The response to the request, as a JavaScript typed array. This is NULL if the request was not successful, or if it hasn't been sent yet. |
multipart Obsolete since Gecko 22 |
boolean |
This Gecko-only feature was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the Note: When this is set, the
onload handler and other event handlers are not reset after the first XMLdocument is loaded, and the onload handler is called after each part of the response is received. |
Constructor
XMLHttpRequest.XMLHttpRequest- The constructor initiates an XMLHttpRequest. It must be called before any other method calls.
Methods
XMLHttpRequest.abort- Aborts the request if it has already been sent.
XMLHttpRequest.getAllResponseHeaders- Returns all the response headers, separated by CRLF, as a string, or
nullif no response has been received. Note: For multipart requests, this returns the headers from the current part of the request, not from the original channel. XMLHttpRequest.getResponseHeader- Returns the string containing the text of the specified header, or
nullif either the response has not yet been received or the header doesn't exist in the response. If there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. ThegetResponseHeader()method returns the value as a UTF byte sequence. XMLHttpRequest.open- Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use
openRequest()instead. XMLHttpRequest.overrideMimeType- Overrides the MIME type returned by the server. This may be used, for example, to force a stream to be treated and parsed as text/xml, even if the server does not report it as such. This method must be called before
send(). XMLHttpRequest.send- Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn't return until the response has arrived.
XMLHttpRequest.setRequestHeader- Sets the value of an HTTP request header. You must call
setRequestHeader()afteropen(), but beforesend(). If this method is called several times with the same header, the values are merged into one single request header.
Non-standard methods
XMLHttpRequest.init- Initializes the object for use from C++ code.
XMLHttpRequest.openRequest- Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use
open()instead. See the documentation foropen().
sendAsBinary()
Deprecated since Gecko 31A variant of the send() method that sends binary data.
send(Blob data) method can be used instead.void sendAsBinary( in DOMString body );
This method, used in conjunction with the readAsBinaryString method of the FileReader API, makes it possible to read and upload any type of file and to stringify the raw data.
Parameters
body- The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).
sendAsBinary() polyfill
Since sendAsBinary() is an experimental feature, here is a polyfill for browsers that don't support the sendAsBinary() method but support typed arrays.
/*\
|*|
|*| :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
|*|
|*| https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
|*|
\*/
if (!XMLHttpRequest.prototype.sendAsBinary) {
XMLHttpRequest.prototype.sendAsBinary = function (sData) {
var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
for (var nIdx = 0; nIdx < nBytes; nIdx++) {
ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
}
/* send as ArrayBufferView...: */
this.send(ui8Data);
/* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
};
}
send(): an ArrayBuffer (ui8Data.buffer – the commented code) or an ArrayBufferView (ui8Data, which is a typed array of 8-bit unsigned integers – uncommented code). However, on Google Chrome, when you try to send an ArrayBuffer, the following warning message will appear: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead. Another possible approach to send binary data is the StringView Non native typed arrays superclass in conjunction with the send() method.Notes
- By default, Firefox 3 limits the number of
XMLHttpRequestconnections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep anXMLHttpRequestconnection open, so opening multiple sessions to such sites may result in the browser hanging in such a way that the window no longer repaints and controls don't respond. This value can be changed by editing thenetwork.http.max-persistent-connections-per-serverpreference inabout:config. - From Gecko 7.0 headers set by
setRequestHeader()are sent with the request when following a redirect. Previously these headers would not be sent. XMLHttpRequestis implemented in Gecko using thensIXMLHttpRequest,nsIXMLHttpRequestEventTarget, andnsIJSXMLHttpRequestinterfaces.- When a request reaches its timeout value, a "timeout" event is raised.
Events
onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.
Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget and Using XMLHttpRequest.
More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.
Permissions
When using System XHR via the mozSystem property, for example for Firefox OS apps, you need to be sure to add the systemXHR permission into your manifest file. System XHR can be used in privileged or certified apps.
"permissions": {
"systemXHR":{}
}
Specifications
| Specification | Status | Comment |
|---|---|---|
| XMLHttpRequest | Living Standard | WHATWG living standard |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support (XHR1) | 1 | 1.0 (1.7 or earlier)[1] | 5[2] 7 |
(Yes) | 1.2 |
send(ArrayBuffer) |
9 | 9.0 (9.0) | 10 | 11.60 | ? |
send(ArrayBufferView) |
22 | 20.0 (20.0) | ? | ? | ? |
send(Blob) |
7 | 3.6 (1.9.2) | 10 | 12 | ? |
send(FormData) |
6 | 4.0 (2.0) | 10 | 12 | ? |
sendAsBinary(DOMString) |
No support[3] | 2.0 (1.8.1) | No support | No support | No support |
response |
10 | 6.0 (6.0) | 10 | 11.60 | (Yes) |
responseType = 'arraybuffer' |
10 | 6.0 (6.0) | 10 | 11.60 | (Yes) |
responseType = 'blob' |
19 | 6.0 (6.0) | 10 | 12 | (Yes) |
responseType = 'document' |
18 | 11.0 (11.0) | 10 | No support | 6.1 |
responseType = 'json' |
31 | 10.0 (10.0) | No support | 12[4] No support 16 17 |
(Yes) |
| Progress Events | 7 | 3.5 (1.9.1) | 10 | 12 | (Yes) |
withCredentials |
3 | 3.5 (1.9.1) | 10 | 12 | 4 |
timeout |
29.0[5] | 12.0 (12.0) | 8 | 12[6] 16 |
(Yes) |
responseType = 'moz-blob' |
No support | 12.0 (12.0) | No support | No support | No support |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | 1.0 | (Yes) | ? | ? | ? |
send(ArrayBuffer) |
? | ? | ? | ? | ? | |
send(ArrayBufferView) |
? | ? | ? | ? | ? | |
send(Blob) |
? | ? | ? | ? | ? | |
send(FormData) |
? | ? | ? | ? | ? | |
sendAsBinary(DOMString) |
? | ? | ? | ? | ? | |
response |
? | ? | ? | ? | ? | |
responseType = 'arraybuffer' |
? | ? | ? | ? | ? | |
responseType = 'blob' |
? | ? | ? | ? | ? | |
responseType = 'document' |
? | ? | ? | ? | ? | |
responseType = 'json' |
? | ? | ? | ? | ? | |
| Progress Events | ? | ? | ? | ? | ? | |
withCredentials |
? | ? | ? | ? | ? | |
timeout |
? | ? | ? | ? | ? | |
responseType = 'moz-blob' |
? | ? | ? | ? | ? |
[1] Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) removed support for using the responseType and withCredentials attributes when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR exception. This change has been proposed to the W3C for standardization.
Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9) and later support using XMLHttpRequest to read from data: URLs.
Gecko 20.0 (Firefox 20.0 / Thunderbird 20.0 / SeaMonkey 2.17) adds the support of sending an ArrayBufferView - sending a plain ArrayBuffer is not part of the XMLHttpRequest specification any longer and should be treated as deprecated.
[2] This feature was implemented via ActiveXObject(). Since version 7 Internet Explorer implements the standard XMLHttpRequest.
[3] There is a polyfill available to support sendAsBinary().
[4] Before switching to Blink/Chromium Opera supported responseType=json between Opera 12 and Opera 15. Support is added again after it is implemented also in Blink (Opera 17).
[5] This feature was implemented in bug 231959.
[6] See how to set and handle timeouts.
See also
- MDN articles about XMLHttpRequest:
- XMLHttpRequest references from W3C and browser vendors:
- W3C: XMLHttpRequest (base features)
- W3C: XMLHttpRequest (latest editor's draft with extensions to the base functionality, formerly XMLHttpRequest Level 2
- Microsoft documentation
- Apple developers' reference
- "Using the XMLHttpRequest Object" (jibbering.com)
- XMLHttpRequest - REST and the Rich User Experience
- HTML5 Rocks - New Tricks in XMLHttpRequest2
- Thread on the naming convention of
XMLHttpRequest Chrome scope availability- how to access from JSM modules etc which do not have access to DOM