XMLHttpRequest

  • Revision slug: DOM/XMLHttpRequest
  • Revision title: XMLHttpRequest
  • Revision id: 314583
  • Created:
  • Creator: matt.kantor
  • Is current revision? No
  • Comment Fix a bunch of in-document anchors for methods.

Revision Content

XMLHttpRequest is a JavaScript object that was designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now being standardized in the W3C. It provides an easy way to retrieve data at a URL. 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).

To create an instance of XMLHttpRequest, simply do this:

var req = new XMLHttpRequest();

For details about how to use XMLHttpRequest, see Using XMLHttpRequest.

Method overview

XMLHttpRequest(JSObject objParameters);
void abort();
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
void overrideMimeType(DOMString mime);
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
void setRequestHeader(DOMString header, DOMString value);
Non-standard methods
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void sendAsBinary(in DOMString body);

Properties

Attribute Type Description

onreadystatechange

Function?

A JavaScript function object that is called whenever the readyState attribute changes. The callback is called from the user interface thread.

Warning: This must not be used from native code. You should also not use this with synchronous requests.
readyState unsigned short

The state of the request:

Value State Description
0 UNSENT open()has not been called yet.
1 OPENED send()has not been called yet.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
response varies

The response entity body according to responseType, as an ArrayBuffer, Blob, {{ domxref("Document") }}, JavaScript object (for "json"), or string. This is null if the request is not complete or was not successful.

responseText DOMString The response to the request as text, or null if the request was unsuccessful or has not yet been sent. Read-only.
responseType XMLHttpRequestResponseType

Can be set to change the response type. This tells the server what format you want the response to be in.

Value Data type of response property
"" (empty string) String (this is the default)
"arraybuffer" ArrayBuffer
"blob" {{ domxref("Blob") }}
"document" {{ domxref("Document") }}
"json" JavaScript object, parsed from a JSON string returned by the server
"text" String
"moz-blob" Used by Firefox to allow retrieving partial {{ domxref("Blob") }} data from progress events. This lets your progress event handler start processing data while it's still being received. {{ gecko_minversion_inline("12.0") }}
Note: Starting with Gecko 11.0 {{ geckoRelease("11.0") }}, as well as WebKit build 528, these browsers no longer let you use the responseType attribute 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.
responseXML Document?

The response to the request as a DOM Document object, or null if 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 a text/xml stream. When the responseType is set to "document" and the request has been made asynchronously, the response is parsed as it were a text/html stream . Read-only.

Note: If the server doesn't apply the text/xml Content-Type header, you can use overrideMimeType()to force XMLHttpRequest to parse it as XML anyway.
status unsigned short The status of the response to the request. This is the HTTP result code (for example, status is 200 for a successful request). Read-only.
statusText DOMString The response string returned by the HTTP server. Unlike status, this includes the entire text of the response message ("200 OK", for example). Read-only.
timeout unsigned long

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. {{ gecko_minversion_inline("12.0") }}

Note: You may not use a timeout for synchronous requests with an owning window.
upload XMLHttpRequestUpload The upload process can be tracked by adding an event listener to upload.
withCredentials boolean

Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers. The default is false.

Note: This never affects same-site requests.
Note: Starting with Gecko 11.0 {{ geckoRelease("11.0") }}, Gecko no longer lets you use the withCredentials attribute when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR exception.

Non-standard properties

Attribute Type Description
channel {{ Interface("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; read-only.
mozBackgroundRequest boolean

Indicates whether or not the object represents a background service request. If true, no load group is associated with the request, and security dialogs are prevented from being shown to the user. Requires elevated privileges to access.

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 {{ gecko_minversion_inline("2.0") }} {{ obsolete_inline("6") }} 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. Read only.
multipart boolean

Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. All requests must be asynchronous.

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 onload handler is called between documents.

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()

The constructor initiates a XMLHttpRequest. It must be called before any other method calls.

Gecko/Firefox 18 (??, see Bug 692677) adds a non-standard parameter to the constructor that can enable anonymous mode. Setting the anon flag to true effectively resembles the AnonXMLHttpRequest() constructor described in the XMLHttpRequest specification which has not been implemented in any browser yet (as of September 2012).

XMLHttpRequest (
  JSObject objParameters
);
Parameters (non-standard)
objParameters {{ gecko_minversion_inline("18.0") }}
There are two flags you can set:
anon
Boolean: Setting this flag to true will cause the browser not to expose the origin and user credentials when fetching resources. Most important, this means that cookies will not be sent unless explicitly added using setRequestHeader.
system
Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting anon: true. I.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Methods

abort()

Aborts the request if it has already been sent.

getAllResponseHeaders()

DOMString getAllResponseHeaders();

Returns all the response headers as a string, or null if 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.

getResponseHeader()

DOMString? getResponseHeader(DOMString header);

Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.

open()

Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest()instead.

Note: Calling this method an already active request (one for which open()or openRequest()has already been called) is the equivalent of calling abort().
void open(
   DOMString method,
   DOMString url,
   optional boolean async,
   optional DOMString user,
   optional DOMString password
);
Parameters
method
The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc. Ignored for non-HTTP(S) URLs.
url
The URL to which to send the request.
async
An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown.
user
The optional user name to use for authentication purposes; by default, this is an empty string.
password
The optional password to use for authentication purposes; by default, this is an empty string.

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().

void overrideMimeType(DOMString mimetype);

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.

Note: Any event listeners you wish to set must be set before calling send().
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Notes

If the data is a Document, it is serialized before being sent. When sending a Document, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; Firefox 3 properly sends the document using the encoding specified by body.xmlEncoding, or UTF-8 if no encoding is specified.

If it's an nsIInputStream, it must be compatible with nsIUploadChannel's setUploadStream()method. In that case, a Content-Length header is added to the request, with its value obtained using nsIInputStream's available()method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the setRequestHeader()method prior to calling send().

setRequestHeader()

Sets the value of an HTTP request header.You must call setRequestHeader() after open(), but before send().

void setRequestHeader(
   DOMString header,
   DOMString value
);
Parameters
header
The name of the header whose value is to be set.
value
The value to set as the body of the header.

Non-standard methods

init()

Initializes the object for use from C++code.

Warning: This method must not be called from JavaScript.
[noscript] void init(
   in nsIPrincipal principal,
   in nsIScriptContext scriptContext,
   in nsPIDOMWindow ownerWindow
);
Parameters
principal
The principal to use for the request; must not be null.
scriptContext
The script context to use for the request; must not be null.
ownerWindow
The window associated with the request; may be null.

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 for open().

{{ method_gecko_minversion("sendAsBinary", "1.9") }}

A variant of the send()method that sends binary data.

void sendAsBinary(
   in DOMString body
);
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).

Notes

  • By default, Firefox 3 limits the number of XMLHttpRequest connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep an XMLHttpRequest connection 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 the network.http.max-persistent-connections-per-server preference in about:config.
  • From {{ gecko("7.0") }} headers set by {{ manch("setRequestHeader") }} are sent with the request when following a redirect. Previously these headers would not be sent.
  • XMLHttpRequest is implemented in Gecko using the {{ interface("nsIXMLHttpRequest") }}, {{ interface("nsIXMLHttpRequestEventTarget") }}, and {{ interface("nsIJSXMLHttpRequest") }} interfaces.

Events

onreadystatechange as a property on the xhr object 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 {{ interface("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.

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (XHR1) 1 1.0 5 (via ActiveXObject)
7 (XMLHttpRequest)
{{ CompatVersionUnknown() }} 1.2
send(ArrayBuffer) 9 9 {{ compatUnknown() }} 11.60 {{ compatUnknown() }}
send(Blob) 7 3.6 {{ compatUnknown() }} 12 {{ compatUnknown() }}
send(FormData) 6 4 {{ compatUnknown() }} 12 {{ compatUnknown() }}
response 10 6 10 11.60 {{ compatUnknown() }}
responseType = 'arraybuffer' 10 6 10 11.60 {{ compatUnknown() }}
responseType = 'blob' 19 6 10 12 {{ compatUnknown() }}
responseType = 'document' 18 11 10 {{ CompatNo() }} {{ CompatNo() }}
responseType = 'json' {{ CompatNo() }} 10 {{ CompatNo() }} 12 {{ CompatNo() }}
Progress Events 7 3.5 10 12 {{ compatUnknown() }}
withCredentials 3 3.5 10 12 4
timeout {{ compatUnknown() }} 12.0 {{ compatVersionUnknown() }} {{ compatUnknown() }} {{ compatUnknown() }}
responseType = 'moz-blob' {{ CompatNo() }} 12.0 {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} 0.16 {{ CompatVersionUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

Gecko notes

Gecko 11.0 {{ geckoRelease("11.0") }} 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 {{ geckoRelease("12.0") }} and later support using XMLHttpRequest to read from data: URLs.

See also

{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "zh-cn/DOM/XMLHttpRequest" } ) }}

Revision Source

<p><code>XMLHttpRequest</code> is a <a class="internal" href="/en/JavaScript" title="En/JavaScript">JavaScript</a> object that was designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now being <a class="external" href="http://www.w3.org/TR/XMLHttpRequest/" title="http://www.w3.org/TR/XMLHttpRequest/">standardized in the W3C</a>. It provides an easy way to retrieve data at a URL. Despite its name, <code>XMLHttpRequest</code> can be used to retrieve any type of data, not just XML, and it supports protocols other than <a href="/en/HTTP" title="en/HTTP">HTTP</a> (including <code>file</code> and <code>ftp</code>).</p>
<p>To create an instance of <code>XMLHttpRequest</code>, simply do this:</p>
<pre>
var req = new XMLHttpRequest();
</pre>
<p>For details about how to use <code>XMLHttpRequest</code>, see <a class="internal" href="/en/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="En/Using XMLHttpRequest">Using XMLHttpRequest</a>.</p>
<h2 id="Method_overview">Method overview</h2>
<table class="standard-table">
  <tbody>
    <tr>
      <td><code><a class="internal" href="/en/DOM/XMLHttpRequest#XMLHttpRequest()" title="/en/DOM/XMLHttpRequest#XMLHttpRequest()">XMLHttpRequest</a>(JSObject objParameters);</code></td>
    </tr>
    <tr>
      <td><code>void <a class="internal" href="/en/DOM/XMLHttpRequest#abort()" title="en/DOM/XMLHttpRequest#abort()">abort</a>();</code></td>
    </tr>
    <tr>
      <td><code>DOMString <a class="internal" href="/en/DOM/XMLHttpRequest#getAllResponseHeaders()" title="en/DOM/XMLHttpRequest#getAllResponseHeaders()">getAllResponseHeaders</a>();</code></td>
    </tr>
    <tr>
      <td><code>DOMString? <a class="internal" href="/en/DOM/XMLHttpRequest#getResponseHeader()" title="en/DOM/XMLHttpRequest#getResponseHeader()">getResponseHeader</a>(DOMString header);</code></td>
    </tr>
    <tr>
      <td><code>void <a class="internal" href="/en/DOM/XMLHttpRequest#open()" title="en/DOM/XMLHttpRequest#open()">open</a>(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);</code></td>
    </tr>
    <tr>
      <td><code>void <a class="internal" href="/en/DOM/XMLHttpRequest#overrideMimeType()" title="en/DOM/XMLHttpRequest#overrideMimeType()">overrideMimeType</a>(DOMString mime);</code></td>
    </tr>
    <tr>
      <td><code>void <a class="internal" href="/en/DOM/XMLHttpRequest#send()" title="en/DOM/XMLHttpRequest#send()">send</a>();</code><br />
        <code>void <a class="internal" href="/en/DOM/XMLHttpRequest#send()" title="en/DOM/XMLHttpRequest#send()">send</a>(ArrayBuffer data);</code><br />
        <code>void <a class="internal" href="/en/DOM/XMLHttpRequest#send()" title="en/DOM/XMLHttpRequest#send()">send</a>(Blob data);</code><br />
        <code>void <a class="internal" href="/en/DOM/XMLHttpRequest#send()" title="en/DOM/XMLHttpRequest#send()">send</a>(Document data);</code><br />
        <code>void <a class="internal" href="/en/DOM/XMLHttpRequest#send()" title="en/DOM/XMLHttpRequest#send()">send</a>(DOMString? data);</code><br />
        <code>void <a class="internal" href="/en/DOM/XMLHttpRequest#send()" title="en/DOM/XMLHttpRequest#send()">send</a>(FormData data);</code></td>
    </tr>
    <tr>
      <td><code>void <a class="internal" href="/en/DOM/XMLHttpRequest#setRequestHeader()" title="en/DOM/XMLHttpRequest#setRequestHeader()">setRequestHeader</a>(DOMString header, DOMString value);</code></td>
    </tr>
    <tr>
      <th>Non-standard methods</th>
    </tr>
    <tr>
      <td><code>[noscript] void <a class="internal" href="/en/DOM/XMLHttpRequest#init()" title="en/DOM/XMLHttpRequest#init()">init</a>(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);</code></td>
    </tr>
    <tr>
      <td><code>[noscript] void <a class="internal" href="/en/DOM/XMLHttpRequest#openRequest()" title="en/DOM/XMLHttpRequest#openRequest()">openRequest</a>(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password); </code></td>
    </tr>
    <tr>
      <td><code>void <a class="internal" href="/en/DOM/XMLHttpRequest#sendAsBinary()" title="en/DOM/XMLHttpRequest#sendAsBinary()">sendAsBinary</a>(in DOMString body);</code></td>
    </tr>
  </tbody>
</table>
<h2 id="Properties">Properties</h2>
<table class="standard-table">
  <tbody>
    <tr>
      <th>Attribute</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
    <tr id="onreadystatechange">
      <td>
        <p><code>onreadystatechange</code></p>
      </td>
      <td><code>Function?</code></td>
      <td>
        <p>A JavaScript function object that is called whenever the <code>readyState</code> attribute changes. The callback is called from the user interface thread.</p>
        <div class="warning">
          <strong>Warning:</strong> This must not be used from native code. You should also not use this with synchronous requests.</div>
      </td>
    </tr>
    <tr id="readyState">
      <td><code>readyState</code></td>
      <td><code>unsigned short</code></td>
      <td>
        <p>The state of the request:</p>
        <table class="standard-table">
          <tbody>
            <tr>
              <td class="header">Value</td>
              <td class="header">State</td>
              <td class="header">Description</td>
            </tr>
            <tr>
              <td><code>0</code></td>
              <td><code>UNSENT</code></td>
              <td><code>open()</code>has not been called yet.</td>
            </tr>
            <tr>
              <td><code>1</code></td>
              <td><code>OPENED</code></td>
              <td><code>send()</code>has not been called yet.</td>
            </tr>
            <tr>
              <td><code>2</code></td>
              <td><code>HEADERS_RECEIVED</code></td>
              <td><code>send()</code> has been called, and headers and status are available.</td>
            </tr>
            <tr>
              <td><code>3</code></td>
              <td><code>LOADING</code></td>
              <td>Downloading; <code>responseText</code> holds partial data.</td>
            </tr>
            <tr>
              <td><code>4</code></td>
              <td><code>DONE</code></td>
              <td>The operation is complete.</td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <tr id="response">
      <td><code>response</code></td>
      <td>varies</td>
      <td>
        <p>The response entity body according to <code><a href="#responseType">responseType</a></code>, as an <a href="/en/JavaScript_typed_arrays/ArrayBuffer" title="en/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="/en/DOM/Blob" title="en/DOM/Blob"><code>Blob</code></a>, {{ domxref("Document") }}, JavaScript object (for "json"), or string. This is <code>null</code> if the request is not complete or was not successful.</p>
      </td>
    </tr>
    <tr id="responseText">
      <td><code>responseText</code></td>
      <td><code>DOMString</code></td>
      <td>The response to the request as text, or <code>null</code> if the request was unsuccessful or has not yet been sent. <strong>Read-only.</strong></td>
    </tr>
    <tr id="responseType">
      <td><code>responseType</code></td>
      <td><code>XMLHttpRequestResponseType</code></td>
      <td>
        <p>Can be set to change the response type. This tells the server what format you want the response to be in.</p>
        <table class="standard-table" style="width: auto;">
          <tbody>
            <tr>
              <td class="header">Value</td>
              <td class="header">Data type of <code>response</code> property</td>
            </tr>
            <tr>
              <td><code>""</code> (empty string)</td>
              <td>String (this is the default)</td>
            </tr>
            <tr>
              <td><code>"arraybuffer"</code></td>
              <td><a href="/en/JavaScript_typed_arrays/ArrayBuffer" title="en/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a></td>
            </tr>
            <tr>
              <td><code>"blob"</code></td>
              <td>{{ domxref("Blob") }}</td>
            </tr>
            <tr>
              <td><code>"document"</code></td>
              <td>{{ domxref("Document") }}</td>
            </tr>
            <tr>
              <td><code>"json"</code></td>
              <td>JavaScript object, parsed from a JSON string returned by the server</td>
            </tr>
            <tr>
              <td><code>"text"</code></td>
              <td>String</td>
            </tr>
            <tr>
              <td><code>"moz-blob"</code></td>
              <td>Used by Firefox to allow retrieving partial {{ domxref("Blob") }} data from progress events. This lets your progress event handler start processing data while it's still being received. {{ gecko_minversion_inline("12.0") }}</td>
            </tr>
          </tbody>
        </table>
        <div class="note">
          <strong>Note:</strong> Starting with Gecko 11.0 {{ geckoRelease("11.0") }}, as well as WebKit build 528, these browsers no longer let you use the <code>responseType</code> attribute when performing synchronous requests. Attempting to do so throws an <code>NS_ERROR_DOM_INVALID_ACCESS_ERR</code> exception. This change has been proposed to the W3C for standardization.</div>
      </td>
    </tr>
    <tr id="responseXML">
      <td><code>responseXML</code></td>
      <td><code>Document?</code></td>
      <td>
        <p>The response to the request as a DOM <code><a class="internal" href="/en/DOM/document" title="En/DOM/Document">Document</a></code> object, or <code>null</code> if 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 a <code>text/xml</code> stream. When the <code>responseType</code> is set to "document" and the request has been made asynchronously, the response is parsed as it were a <code>text/html</code> stream . <strong>Read-only.</strong></p>
        <div class="note">
          <strong>Note:</strong> If the server doesn't apply the <code>text/xml</code> Content-Type header, you can use <code>overrideMimeType()</code>to force <code>XMLHttpRequest</code> to parse it as XML anyway.</div>
      </td>
    </tr>
    <tr id="status">
      <td><code>status</code></td>
      <td><code>unsigned short</code></td>
      <td>The status of the response to the request. This is the HTTP result code (for example, <code>status</code> is 200 for a successful request). <strong>Read-only.</strong></td>
    </tr>
    <tr id="statusText">
      <td><code>statusText</code></td>
      <td><code>DOMString</code></td>
      <td>The response string returned by the HTTP server. Unlike <code>status</code>, this includes the entire text of the response message ("<code>200 OK</code>", for example). <strong>Read-only.</strong></td>
    </tr>
    <tr id="timeout">
      <td><code>timeout</code></td>
      <td><code>unsigned long</code></td>
      <td>
        <p>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. {{ gecko_minversion_inline("12.0") }}</p>
        <div class="note">
          <strong>Note:</strong> You may not use a timeout for synchronous requests with an owning window.</div>
      </td>
    </tr>
    <tr id="upload">
      <td><code>upload</code></td>
      <td><code>XMLHttpRequestUpload</code></td>
      <td>The upload process can be tracked by adding an event listener to <code>upload</code>.</td>
    </tr>
    <tr id="withCredentials">
      <td><code>withCredentials</code></td>
      <td><code>boolean</code></td>
      <td>
        <p>Indicates whether or not cross-site <code>Access-Control</code> requests should be made using credentials such as cookies or authorization headers. The default is <code>false</code>.</p>
        <div class="note">
          <strong>Note:</strong> This never affects same-site requests.</div>
        <div class="note">
          <strong>Note:</strong> Starting with Gecko 11.0 {{ geckoRelease("11.0") }}, Gecko no longer lets you use the <code>withCredentials</code> attribute when performing synchronous requests. Attempting to do so throws an <code>NS_ERROR_DOM_INVALID_ACCESS_ERR</code> exception.</div>
      </td>
    </tr>
  </tbody>
</table>
<h3 id="Non-standard_properties">Non-standard properties</h3>
<table class="standard-table">
  <tbody>
    <tr>
      <th>Attribute</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
    <tr id="channel">
      <td><code>channel</code></td>
      <td>{{ Interface("nsIChannel") }}</td>
      <td>The channel used by the object when performing the request. This is <code>null</code> 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. <strong>Requires elevated privileges to access; read-only.</strong></td>
    </tr>
    <tr id="mozBackgroundRequest">
      <td><code>mozBackgroundRequest</code></td>
      <td><code>boolean</code></td>
      <td>
        <p>Indicates whether or not the object represents a background service request. If <code>true</code>, no load group is associated with the request, and security dialogs are prevented from being shown to the user. <strong>Requires elevated privileges to access.</strong></p>
        <p>In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead.</p>
        <div class="note">
          <strong>Note: </strong>This property must be set before calling <code>open()</code>.</div>
      </td>
    </tr>
    <tr id="mozResponseArrayBuffer">
      <td><code>mozResponseArrayBuffer</code> {{ gecko_minversion_inline("2.0") }} {{ obsolete_inline("6") }}</td>
      <td><a href="/en/JavaScript_typed_arrays/ArrayBuffer" title="en/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a></td>
      <td>The response to the request, as a JavaScript typed array. This is NULL&nbsp;if the request was not successful, or if it hasn't been sent yet. <strong>Read only.</strong></td>
    </tr>
    <tr id="multipart">
      <td><code>multipart</code></td>
      <td><code>boolean</code></td>
      <td>
        <p>Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to <code>true</code>, the content type of the initial response must be <code>multipart/x-mixed-replace</code> or an error will occur. All requests must be asynchronous.</p>
        <p>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 <code>onload</code> handler is called between documents.</p>
        <div class="note">
          <strong>Note:</strong> When this is set, the <code>onload</code> handler and other event handlers are not reset after the first XMLdocument is loaded, and the <code>onload</code> handler is called after each part of the response is received.</div>
      </td>
    </tr>
  </tbody>
</table>
<h2 id="Constructor">Constructor</h2>
<h3 id="XMLHttpRequest()" name="XMLHttpRequest()">XMLHttpRequest()</h3>
<p>The constructor initiates a XMLHttpRequest. It must be called before any other method calls.</p>
<p>Gecko/Firefox 18 (??, see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=692677" title="692677 – Relax same-origin XHR restrictions for privileged applications">Bug 692677</a>) adds a non-standard parameter to the constructor that can enable anonymous mode. Setting the <code>anon</code> flag to <code>true</code> effectively resembles the <a href="http://www.w3.org/TR/2012/WD-XMLHttpRequest-20120117/#dom-anonxmlhttprequest" title="see AnonXMLHttpRequest in the XMLHttpRequest specification"><code>AnonXMLHttpRequest()</code></a> constructor described in the XMLHttpRequest specification which has not been implemented in any browser yet (as of September 2012).</p>
<pre>
XMLHttpRequest (
  JSObject objParameters
);</pre>
<h5 id="Parameters_(non-standard)">Parameters (non-standard)</h5>
<dl>
  <dt>
    <code>objParameters</code> {{ gecko_minversion_inline("18.0") }}</dt>
  <dd>
    There are two flags you can set:
    <dl>
      <dt>
        <code>anon</code></dt>
      <dd>
        Boolean: Setting this flag to <code>true</code> will cause the browser not to expose the origin and <a href="http://www.w3.org/TR/2012/WD-XMLHttpRequest-20120117/#user-credentials" title="Defintion of “User credentials” in the XMLHttpRequest specification.">user credentials</a> when fetching resources. Most important, this means that cookies will not be sent unless explicitly added using setRequestHeader.</dd>
      <dt>
        <code>system</code></dt>
      <dd>
        Boolean: Setting this flag to <code>true</code> allows making cross-site connections without requiring the server to opt-in using CORS. <em>Requires setting <code>anon: true</code>. I.e. this can't be combined with sending cookies or other user credentials. This <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=692677#c68" title="Bug 692677 comment 68">only works in privileged (reviewed) apps</a>; it does not work on arbitrary webpages loaded in Firefox.</em></dd>
    </dl>
  </dd>
</dl>
<h2 id="Methods">Methods</h2>
<h3 id="abort()" name="abort()">abort()</h3>
<p>Aborts the request if it has already been sent.</p>
<h3 id="getAllResponseHeaders()" name="getAllResponseHeaders()">getAllResponseHeaders()</h3>
<pre>
DOMString getAllResponseHeaders();</pre>
<p>Returns all the response headers as a string, or <code>null</code> if no response has been received.<strong> Note:</strong> For multipart requests, this returns the headers from the <em>current</em> part of the request, not from the original channel.</p>
<h3 id="getResponseHeader()" name="getResponseHeader()">getResponseHeader()</h3>
<pre>
DOMString? getResponseHeader(DOMString <var>header</var>);</pre>
<p>Returns the string containing the text of the specified header, or <code>null</code> if either the response has not yet been received or the header doesn't exist in the response.</p>
<h3 id="open()" name="open()">open()</h3>
<p>Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use <a class="internal" href="/en/nsIXMLHttpRequest#openRequest()" title="/en/XMLHttpRequest#openRequest()"><code>openRequest()</code></a>instead.</p>
<div class="note">
  <strong>Note:</strong> Calling this method an already active request (one for which <code>open()</code>or <code>openRequest()</code>has already been called) is the equivalent of calling <code>abort()</code>.</div>
<pre>
void open(
   DOMString <var>method</var>,
   DOMString <var>url</var>,
   optional boolean <var>async</var>,
   optional DOMString <var>user</var>,
   optional DOMString <var>password</var>
);
</pre>
<h6 id="Parameters">Parameters</h6>
<dl>
  <dt>
    <code>method</code></dt>
  <dd>
    The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc. Ignored for non-HTTP(S) URLs.</dd>
  <dt>
    <code>url</code></dt>
  <dd>
    The URL to which to send the request.</dd>
  <dt>
    <code>async</code></dt>
  <dd>
    An optional boolean parameter, defaulting to <code>true</code>, indicating whether or not to perform the operation asynchronously. If this value is <code>false</code>, the <code>send()</code>method does not return until the response is received. If <code>true</code>, notification of a completed transaction is provided using event listeners. This <em>must</em> be true if the <code>multipart</code> attribute is <code>true</code>, or an exception will be thrown.</dd>
  <dt>
    <code>user</code></dt>
  <dd>
    The optional user name to use for authentication purposes; by default, this is an empty string.</dd>
  <dt>
    <code>password</code></dt>
  <dd>
    The optional password to use for authentication purposes; by default, this is an empty string.</dd>
</dl>
<h3 id="overrideMimeType()" name="overrideMimeType()">overrideMimeType()</h3>
<p>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 <code>send()</code>.</p>
<pre>
void overrideMimeType(DOMString <var>mimetype</var>);</pre>
<h3 id="send()" name="send()">send()</h3>
<p>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.</p>
<div class="note">
  <strong>Note:</strong> Any event listeners you wish to set must be set before calling <code>send()</code>.</div>
<pre>
void send();
void send(ArrayBuffer <var>data</var>);
void send(Blob <var>data</var>);
void send(Document <var>data</var>);
void send(DOMString? <var>data</var>);
void send(FormData <var>data</var>);</pre>
<h6 id="Notes">Notes</h6>
<p>If the <var>data</var> is a <code>Document</code>, it is serialized before being sent. When sending a Document, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; <a href="/en/Firefox_3" rel="internal" title="en/Firefox_3">Firefox 3</a> properly sends the document using the encoding specified by <code>body.xmlEncoding</code>, or UTF-8 if no encoding is specified.</p>
<p>If it's an <code>nsIInputStream</code>, it must be compatible with <code>nsIUploadChannel</code>'s <code>setUploadStream()</code>method. In that case, a Content-Length header is added to the request, with its value obtained using <code>nsIInputStream</code>'s <code>available()</code>method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the <a class="internal" href="/en/nsIXMLHttpRequest#setRequestHeader()" title="/en/XMLHttpRequest#setRequestHeader()"><code>setRequestHeader()</code></a>method prior to calling <code>send()</code>.</p>
<h3 id="setRequestHeader()" name="setRequestHeader()">setRequestHeader()</h3>
<p>Sets the value of an HTTP request header.You must call <code>setRequestHeader()</code> after&nbsp;<a href="#open"><code>open()</code></a>, but before <code>send()</code>.</p>
<pre>
void setRequestHeader(
   DOMString <var>header</var>,
   DOMString <var>value</var>
);
</pre>
<h6 id="Parameters">Parameters</h6>
<dl>
  <dt>
    <code>header</code></dt>
  <dd>
    The name of the header whose value is to be set.</dd>
  <dt>
    <code>value</code></dt>
  <dd>
    The value to set as the body of the header.</dd>
</dl>
<h3 id="Non-standard_methods">Non-standard methods</h3>
<h4 id="init()">init()</h4>
<p>Initializes the object for use from C++code.</p>
<div class="warning">
  <strong>Warning:</strong> This method must <em>not</em> be called from JavaScript.</div>
<pre>
[noscript] void init(
   in nsIPrincipal principal,
   in nsIScriptContext scriptContext,
   in nsPIDOMWindow ownerWindow
);
</pre>
<h5 id="Parameters">Parameters</h5>
<dl>
  <dt>
    <code>principal</code></dt>
  <dd>
    The principal to use for the request; must not be <code>null</code>.</dd>
  <dt>
    <code>scriptContext</code></dt>
  <dd>
    The script context to use for the request; must not be <code>null</code>.</dd>
  <dt>
    <code>ownerWindow</code></dt>
  <dd>
    The window associated with the request; may be <code>null</code>.</dd>
</dl>
<h4 id="openRequest()">openRequest()</h4>
<p>Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use <a class="internal" href="/en/nsIXMLHttpRequest#open()" title="/en/XMLHttpRequest#open()"><code>open()</code></a>instead. See the documentation for <code>open()</code>.</p>
<p>{{ method_gecko_minversion("sendAsBinary", "1.9") }}</p>
<p>A variant of the <code>send()</code>method that sends binary data.</p>
<pre>
void sendAsBinary(
   in DOMString body
);
</pre>
<h5 id="Parameters">Parameters</h5>
<dl>
  <dt>
    <code>body</code></dt>
  <dd>
    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).</dd>
</dl>
<h2 id="Notes">Notes</h2>
<ul>
  <li class="note">By default, Firefox 3 limits the number of <code>XMLHttpRequest</code> connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep an <code>XMLHttpRequest</code> connection 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 the <code>network.http.max-persistent-connections-per-server</code> preference in <code><a class="linkification-ext" href="/about:config" title="Linkification: about:config">about:config</a></code>.</li>
  <li class="note">From {{ gecko("7.0") }} headers set by {{ manch("setRequestHeader") }} are sent with the request when following a redirect. Previously these headers would not be sent.</li>
  <li class="note"><code>XMLHttpRequest</code> is implemented in Gecko using the {{ interface("nsIXMLHttpRequest") }}, {{ interface("nsIXMLHttpRequestEventTarget") }}, and {{ interface("nsIJSXMLHttpRequest") }} interfaces.</li>
</ul>
<h4 class="note" id="Events">Events</h4>
<p><code>onreadystatechange</code> as a property on the xhr object is supported in all browsers.</p>
<p>Since then, a number of additional event handlers were implemented in various browsers (<code>onload</code>, <code>onerror</code>, <code>onprogress</code>, etc.). These are supported in Firefox. In particular, see {{ interface("nsIXMLHttpRequestEventTarget") }} and <a href="/en/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="En/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a>.</p>
<p>More recent browsers, including Firefox, also support listening to the <code>XMLHttpRequest</code> events via standard <code><a href="/en/DOM/element.addEventListener" title="element.addEventListener">addEventListener</a></code> APIs in addition to setting <code>on*</code> properties to a handler function.</p>
<h2 id="Browser_Compatibility" name="Browser_Compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari (WebKit)</th>
      </tr>
      <tr>
        <td>Basic support (XHR1)</td>
        <td>1</td>
        <td>1.0</td>
        <td>5 (via ActiveXObject)<br />
          7 (XMLHttpRequest)</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>1.2</td>
      </tr>
      <tr>
        <td><code>send(ArrayBuffer)</code></td>
        <td>9</td>
        <td>9</td>
        <td>{{ compatUnknown() }}</td>
        <td>11.60</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>send(Blob)</code></td>
        <td>7</td>
        <td>3.6</td>
        <td>{{ compatUnknown() }}</td>
        <td>12</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>send(FormData)</code></td>
        <td>6</td>
        <td>4</td>
        <td>{{ compatUnknown() }}</td>
        <td>12</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>response</code></td>
        <td>10</td>
        <td>6</td>
        <td>10</td>
        <td>11.60</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>responseType</code> = 'arraybuffer'</td>
        <td>10</td>
        <td>6</td>
        <td>10</td>
        <td>11.60</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>responseType</code> = 'blob'</td>
        <td>19</td>
        <td>6</td>
        <td>10</td>
        <td>12</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>responseType</code> = 'document'</td>
        <td>18</td>
        <td>11</td>
        <td>10</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
      </tr>
      <tr>
        <td><code>responseType</code> = 'json'</td>
        <td>{{ CompatNo() }}</td>
        <td>10</td>
        <td>{{ CompatNo() }}</td>
        <td>12</td>
        <td>{{ CompatNo() }}</td>
      </tr>
      <tr>
        <td>Progress Events</td>
        <td>7</td>
        <td>3.5</td>
        <td>10</td>
        <td>12</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>withCredentials</code></td>
        <td>3</td>
        <td>3.5</td>
        <td>10</td>
        <td>12</td>
        <td>4</td>
      </tr>
      <tr>
        <td><code>timeout</code></td>
        <td>{{ compatUnknown() }}</td>
        <td>12.0</td>
        <td>{{ compatVersionUnknown() }}</td>
        <td>{{ compatUnknown() }}</td>
        <td>{{ compatUnknown() }}</td>
      </tr>
      <tr>
        <td><code>responseType</code> = 'moz-blob'</td>
        <td>{{ CompatNo() }}</td>
        <td>12.0</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE&nbsp;Phone</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown() }}</td>
        <td>0.16</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<h3 id="Gecko_notes">Gecko notes</h3>
<p>Gecko 11.0 {{ geckoRelease("11.0") }} removed support for using the <code>responseType</code> and <code>withCredentials</code> attributes when performing synchronous requests. Attempting to do so throws an <code>NS_ERROR_DOM_INVALID_ACCESS_ERR</code> exception. This change has been proposed to the W3C for standardization.</p>
<p>Gecko 12.0 {{ geckoRelease("12.0") }} and later support using <code>XMLHttpRequest</code> to read from <a href="/en/data_URIs" title="en/data_URIs"><code>data:</code> URLs</a>.</p>
<h2 id="See_also">See also</h2>
<ul>
  <li>MDN articles about XMLHttpRequest:
    <ul>
      <li><a href="/en/AJAX/Getting_Started" title="en/AJAX/Getting_Started">AJAX - Getting Started</a></li>
      <li><a href="/en/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="En/Using XMLHttpRequest">Using XMLHttpRequest</a></li>
      <li><a href="/en/HTML_in_XMLHttpRequest" title="en/HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a></li>
      <li><a href="/en/DOM/XMLHttpRequest/FormData" title="en/XMLHttpRequest/FormData"><code>FormData</code></a></li>
    </ul>
  </li>
  <li>XMLHttpRequest references from W3C and browser vendors:
    <ul>
      <li><a class="external" href="http://www.w3.org/TR/XMLHttpRequest1/">W3C: XMLHttpRequest</a> (base features)</li>
      <li><a class="external" href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html" title="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html">W3C: XMLHttpRequest</a> (latest editor's draft with extensions to the base functionality, formerly XMLHttpRequest Level 2</li>
      <li><a class="external" href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp">Microsoft documentation</a></li>
      <li><a class="external" href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html">Apple developers' reference</a></li>
    </ul>
  </li>
  <li><a class="external" href="http://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li>
  <li><a class="external" href="http://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li>
  <li><a class="external" href="http://www.html5rocks.com/en/tutorials/file/xhr2/">HTML5 Rocks - New Tricks in XMLHttpRequest2</a></li>
</ul>
<p>{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "zh-cn/DOM/XMLHttpRequest" } ) }}</p>
Revert to this revision