The XMLHttpRequest Object

W3C Working Draft 27 February 2007

This Version:
Latest Version:
Previous Versions:
Anne van Kesteren (Opera Software ASA) <annevk@opera.com>


The XMLHttpRequest Object specification defines an API that provides scripted client functionality for transferring data between a client and a server.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 27 February 2007 Last Call Working Draft of The XMLHttpRequest Object specifcation. Please send comments to public-webapi@w3.org (archived) with either [XHR] or [XMLHttpRequest] at the start of the subject line by 2 April 2007.

This document is produced by the Web API Working Group, part of the Rich Web Clients Activity in the W3C Interaction Domain. Changes made to this document can be found in the W3C public CVS server.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

The XMLHttpRequest object implements an interface exposed by a scripting engine that allows scripts to perform HTTP client functionality, such as submitting form data or loading data from a server.

The name of the object is XMLHttpRequest for compatibility with the web, though each component of this name is potentially misleading. First, the object supports any text based format, including XML. Second, it can be used to make requests over both HTTP and HTTPS (some implementations support protocols in addition to HTTP and HTTPS, but that functionality is not covered by this specification). Finally, it supports "requests" in a broad sense of the term as it pertains to HTTP; namely all activity involved with HTTP requests or responses for the defined HTTP methods.

1.1. Examples of Usage

This section is non-normative.

Some [ECMAScript] examples are listed in the specification. In addition, you can find some below.

Some simple code to do something with data from an XML document fetched over the network:

function test(data) {
 // taking care of data

function handler() {
 if(this.readyState == 4 && this.status == 200) {
  // so far so good
  if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
   // success!
 } else if (this.readyState == 4 && this.status != 200) {
  // fetched the wrong page or network error...

var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");

If you just want to ping the server with a message you could do something like:

function ping(message) {
 var client = new XMLHttpRequest();
 client.open("POST", "/ping");

Or if you want to check the status of a document on the server:

function fetchStatus(address) {
 var client = new XMLHttpRequest();
 client.onreadystatechange = function() {
  // in case of network errors this might not give reliable results
  if(this.readyState == 4)
 client.open("HEAD", address);

1.2. Conformance

Everything in this specification is normative except for diagrams, examples, notes and sections marked non-normative.

The key words must, must not, required, shall, shall not, should, should not, recommended, may and optional in this document are to be interpreted as described in RFC 2119 [RFC2119].

This specification defines the following classes of products:

conforming implementation
A user agent must behave as described in this specification in order to be considered conformant even when faced with non-conforming scripts.
conforming script
A script must satisfy the constrains and conditions described by this specification in order to be conformant.

1.2.1. Dependencies

This specification relies on several underlying specifications.


Implementations must support some version of DOM Events because this specification uses some of the features defined in that specification. [DOM3Events]

Implementations must support some version of DOM Core because this specification uses some of the features defined in that specification. [DOM3Core]

Implementations must support some version of the Window Object because some of the functionality in this specification relies on it. [Window]


Implementations must support some version of the HTTP protocol. Other requirements regarding HTTP are made throughout the specification. [RFC2616]


Implementations may support some version of XML. If they don't support some version of XML responseXML must always be null. [XML] [XMLNS]

1.3. Extensibility

This section is non-normative.

Extensions of the APIs defined by this specification are strongly discouraged. User agents, Working Groups and other interested parties should discuss extensions on a relevant public forum, preferably public-webapi@w3.org.

2. The XMLHttpRequest Object

The XMLHttpRequest interface can be used by scripts to programmatically connect to their originating server via HTTP.

Objects implementing the XMLHttpRequest interface must also implement the EventTarget interface [DOM3Events].

In [ECMAScript], an instance of XMLHttpRequest can be created using the XMLHttpRequest() constructor:

var client = new XMLHttpRequest();

When the constructor is invoked a pointer to the Window object which initially had XMLHttpRequest as an attribute of which the constructor was invoked must be stored on the newly created object, called the Window pointer. This pointer must persist even if the browsing context in which the Window is located is destroyed (by removing it from a parent browsing context, for instance).

The term browsing context is defined by the Window Object 1.0 specification. [Window]

2.1. Members of the XMLHttpRequest Object

interface XMLHttpRequest {
           attribute EventListener   onreadystatechange;
  readonly attribute unsigned short  readyState;
  void               open(in DOMString method, in DOMString url);
  void               open(in DOMString method, in DOMString url, in boolean async);
  void               open(in DOMString method, in DOMString url, in boolean async, in DOMString user);
  void               open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password);
  void               setRequestHeader(in DOMString header, in DOMString value);
  void               send();
  void               send(in DOMString data);
  void               send(in Document data);
  void               abort();
  DOMString          getAllResponseHeaders();
  DOMString          getResponseHeader(in DOMString header);
  readonly attribute DOMString       responseText;
  readonly attribute Document        responseXML;
  readonly attribute unsigned short  status;
  readonly attribute DOMString       statusText;
onreadystatechange of type EventListener

An attribute that takes an EventListener as value that must be invoked when readystatechange is dispatched on the object implementing the XMLHttpRequest interface. Its initial value must be null.

readyState of type unsigned short, readonly

The state of the object. The attribute must be one of the following values:

0 Uninitialized
The initial value.
1 Open
The open() method has been successfully called.
2 Sent
The user agent successfully acknowledged the request.
3 Receiving
Immediately before receiving the message body (if any). All HTTP headers have been received.
4 Loaded
The data transfer has been completed.

When readyState changes value a readystatechange event is to be dispatched on the XMLHttpRequest object.

open(method, url, async, user, password), method

Invoking this method must initialize the object by remembering the method, url, async (defaulting to true if omitted), user (defaulting to null if omitted), and password (defaulting to null if omitted) arguments, setting the state to open, resetting the responseText, responseXML, status, and statusText attributes to their initial values, and resetting the list of request headers.

In addition, when the state is not uninitialized, all members of the object with the exception of onreadystate must be set to their initial values and user agents must behave as if abort() was invoked.

If the method argument doesn't match the Method production defined in section 5.1.1 of RFC 2616 a SYNTAX_ERR must be raised by the user agent. If the user agent doesn't support the given method for security reasons a SECURITY_ERR should be raised. [RFC2616]

User agents must at least support the following list of methods (see [RFC2616]):

User agents should support any method argument that matches the Method production.

When method case-insensitively matches GET, POST, HEAD, PUT or DELETE user agents must use the uppercase equivalent instead.

When url is a relative reference, it must be resolved using the current value of the baseURI attribute of the Document object currently associated with the Window pointer and the fragment identifier component, if any, must be dropped. If it can't be resolved user agents must throw a SYNTAX_ERR. When a non same-origin url argument is given user agents should throw a SECURITY_ERR exception.

A future version or extension of this specification will most likely define a way of doing cross-site requests.

User agents should not support the "user:password" format in the userinfo production defined in section 3.2.1 of RFC 3986 and must throw a SYNTAX_ERR when doing so (not supporting it). When they do support it, or in case of people using the format "user", user agents must use them if the user and password arguments are omitted. If the arguments are not omitted, they take precedence, even if they are null. [RFC3986]

The syntax for the user or password arguments depends on the scheme being used. If the syntax for either is incorrect per the production given in the relevant scheme user agents must throw a SYNTAX_ERR exception. The user and password must be encoded using the encoding specified by the scheme. If the scheme fails to specify an encoding they must be encoded using UTF-8.

When null is passed for either user or password user agents must act as if the relevant data (the user name or password) is not provided.

The empty string value is not to be treated as the null value. If it's disallowed by the syntax for either user or password a SYNTAX_ERR has to be thrown as indicated above.

setRequestHeader(header, value), method

Each request has a list of request headers with associated values. This method can be used to manipulate those values and set new request headers.

The nominated request header (header) field value must be set to value, with the following exceptions:

Implementations must replace any existing value if the header argument case-insensitively matches one of:

The value of other headers cannot be reset, additional values will be appended to the existing value instead.

Otherwise, if the header argument does not match any of the listed headers and already has a value that value must be retained. User agents may either use multiple headers, combine the values or use a combination of those (section 4.2, RFC 2616). [RFC2616]

See also the send() method regarding user agent header handling for caching, authentication, proxies, and cookies.

// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'demo.cgi');
client.setRequestHeader('X-Test', 'one');
client.setRequestHeader('X-Test', 'two');

// ...would result in the following header being sent:
X-Test: one, two

The list of request headers must be reset when the open() method is invoked.

send(data), method

If the state is not open or the send() flag is set an INVALID_STATE_ERR exception must be raised. Otherwise user agents must make a request to url using method method and set the send() flag. If the async flag is set to false, then the method must not return until the request has completed. Otherwise, it must return immediately. (See: open().)

Even when async is set to false the readystatechange event will still be dispatched.

The send() flag is only relevant when the state is open.

If data is passed to the send() method it must be used for the entity body as defined by section 7.2 of [RFC2616] The following rules apply:

data is a DOMString
data must be encoded as UTF-8 for transmission.
data is a Document

data must be serialized into a namespace well-formed XML document and encoded using the encoding given by data.xmlEncoding, if specified, or UTF-8 otherwise. If this fails because the Document cannot be serialized user agents must act as if data was null.

Subsequent changes to the Document have no effect on what is submitted.

data is not a DOMString or Document
The stringification mechanisms of the host language must be used on data and the result must be treated as if data is a DOMString.

Invoking send() without the data argument must give the same result as if it was invoked with null as argument.

Scripts should specify the Content-Type header via setRequestHeader before invoking send() with an argument. If the argument to send() is a Document and no Content-Type header has been set user agents must set it to application/xml for XML documents and to the most appropriate media type for other documents (using intrinsic knowledge about the document).

If the response is an HTTP redirect (status code 301, 302, 303 or 307), then it must be transparently followed (unless it violates security, infinite loop precautions or the scheme isn't supported).

HTTP places requirements on user agents regarding the preservation of the request method and entity body during redirects, and also requires users to be notified of certain kinds of automatic redirections.

Once the request has been successfully acknowledged the state must be set to sent. Immediately before receiving the message body (if any), the state must be set to to receiving. When the request has completed loading, the state must be set to loaded.

This means that in case of a HEAD request the state is set to loaded immediately after having being set to receiving.

If something goes wrong (infinite loop, network errors) the state must be set to loaded and all members (excluding readyState) of the object must be set to their initial value. Also, if async is set to false, a NETWORK_ERR exception must be raised. In addition, all registered event listeners must be removed.

In future versions of this specification user agents will be required to dispatch an error event if the above occurs.

If the user agent allows the specification of a proxy it should modify the request appropriately; i.e., connect to the proxy host instead of the origin server, modify the Request-Line and send Proxy-Authorization headers as specified.

If the user agent supports HTTP Authentication it should consider requests originating from this object to be part of the protection space that includes the accessed URIs and send Authorization headers and handle 401 Unauthorised requests appropriately. if authentication fails, user agents should prompt the users for credentials. [RFC2617]

If the user agent supports HTTP State Mangement it should persist, discard and send cookies (as received in the Set-Cookie and Set-Cookie2 response headers, and sent in the Cookie header) as applicable. [RFC2965]

If the user agent implements a HTTP cache it should respect Cache-Control request headers set by the script (e.g., Cache-Control: no-cache bypasses the cache). It must not send Cache-Control or Pragma request headers automatically unless the user explicitly requests such behaviour (e.g., by (force-)reloading the page). 304 Not Modified responses that are a result of a user agent generated conditional request must be presented as 200 OK responses with the appropriate content. Such user agents must allow scripts to override automatic cache validation by setting request headers (e.g., If-None-Match, If-Modified-Since), in which case 304 Not Modified responses must be passed through. [RFC2616]

If the user agent implements server-driven content-negotiation it should set Accept-Language, Accept-Encoding and Accept-Charset headers as appropriate; it must not automatically set the Accept header. Responses to such requests must have the content-codings automatically decoded. [RFC2616]

abort(), method

When invoked, this method must cancel any network activity for which the object is responsible and set all the members of the object to their initial values as well as removing all event listeners.

This means that the object can be used for another request in which case this method will work again to cancel it.

getAllResponseHeaders(), method

If the state is not receiving or loaded, user agents must raise an INVALID_STATE_ERR exception. Otherwise, it must return all the HTTP headers, as a single string, with each header line separated by a CR (U+000D) LF (U+000A) pair. The status line must not be included.

// The following script:
var client = new XMLHttpRequest();
client.open("GET", "test.txt", true);
client.onreadystatechange = function() {
 if(this.readyState == 3) {

// ...should output something similar to the following text:
Date: Sun, 24 Oct 2004 04:58:38 GMT
Server: Apache/1.3.31 (Unix)
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8
getResponseHeader(header), method

If the header argument doesn't match the field-name production a SYNTAX_ERR must be raised. Otherwise this method works as described below.

If the state is not receiving or loaded, the user agent must raise an INVALID_STATE_ERR exception. Otherwise, it must represent the value of the given HTTP header (header) in the data received so far for the last request sent, as a single string. If more than one header of the given name was received, then the values must be concatenated, separated from each other by an U+002C COMMA followed by an U+0020 SPACE. If no headers of that name were received, then it must return null. Header names must be compared case-insensitively to the method's argument (header).

// The following script:
var client = new XMLHttpRequest();
client.open("GET", "test.txt", true);
client.onreadystatechange = function() {
 if(this.readyState == 3) {

// ...should output something similar to the following text:
Content-Type: text/plain; charset=utf-8
responseText of type DOMString, readonly

If the state is not receiving or loaded, the user agent must raise an INVALID_STATE_ERR exception. Otherwise, if there's no entity body this attribute must be null. If there is, it must be the fragment of the entity body received so far (when the state is receiving) or the complete entity body (when the state is loaded), interpreted as a stream of characters.

If the response includes a MIME type understood by the user agent the characters must be decoded following the relevant MIME type specification. If the user agent cannot derive a character stream in accord with the media type specification, responseText must be null.

Its initial value must be the null.

responseXML of type Document, readonly

If the state is not loaded, user agents must raise an INVALID_STATE_ERR exception. Otherwise, if there's no entity body this attribute must be null. If there is, and the Content-Type header contains a media type (ignoring any parameters) that is either text/xml, application/xml, or ends in +xml, it must be an object that implements the Document interface representing the parsed document. If Content-Type did not contain such a media type, or if the document could not be parsed (due to an XML namespace well-formedness error or unsupported character encoding, for instance), it must be null.

Its initial value must be null.

status of type unsigned short, readonly

If the status attribute is not available an INVALID_STATE_ERR exception must be raised. It must be available when the state is receiving or loaded. When available, it must represent the HTTP status code (typically 200 for a successful request).

Its initial value must be 0.

statusText of type DOMString, readonly

If the statusText attribute is not available an INVALID_STATE_ERR exception must be raised. It must be available when the state is receiving or loaded). When available, it must represent the HTTP status text sent by the server (appears after the status code).

Its initial value must be the empty string.

HTTP requests sent from multiple different XMLHttpRequest objects in succession should use a shared HTTP connection.

2.2. Events for the XMLHttpRequest Object

These sections describe the various events that can be dispatched on the object implementing the XMLHttpRequest interface. For this version of the specification only one event is defined.

The readystatechange event must be dispatched when readyState changes value. It must not bubble, must not be cancelable and must implement the Event interface. The event has no namespace (Event.namespaceURI is null). [DOM3Events]

2.3. Exceptions for the XMLHttpRequest Object

exception XMLHttpRequestException {
  unsigned short     code;
const unsigned short NETWORK_ERR = 101;

The NETWORK_ERR exception is thrown when a network error occurs in synchronous requests. See the section on send() for more details.

Not in this Specification

This section is non normative.

This specification does not include the following features that may or may not be implemented by user agents:


Document Object Model (DOM) Level 3 Core Specification, A. Le Hors, P. Le Hégaret, L. Wood, G. Nicol, J. Robie, M. Champion, S. Byrne, editors. World Wide Web Consortium, April 2004.
Document Object Model (DOM) Level 3 Events Specification, Björn Höhrmann, editor. World Wide Web Consortium, April 2006.
ECMAScript Language Specification, Third Edition. ECMA, December 1999.
Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein, editors. IETF, November 1996.
RFC 2119: Key words for use in RFCs to Indicate Requirement Levels, S. Bradner. IETF, March 1997.
Hypertext Transfer Protocol -- HTTP/1.1, R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, T. Berners-Lee, editors. IETF, June 1999
HTTP Authentication: Basic and Digest Access Authentication, ...
HTTP State Management Mechanism, D. Kristol, L. Montulli, editors. IETF, October 2000.
Uniform Resource Identifier (URI): Generic Syntax, T. Berners-Lee, R. Fielding, L. Masinter, editors. IETF, January 2005.
Window Object 1.0, I. Davis, M. Stachowiak, editors. W3C, April 2006.
Extensible Markup Language (XML) 1.0 (Fourth Edition), T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau. W3C, September 2006.
Namespaces in XML (Second Edition), T. Bray, D. Hollander, A. Layman, R. Tobin. W3C, August 2006.


This section is non-normative

The editor would like to thank to the following people who have contributed to this specification (ordered by first name):

Special thanks to the Microsoft employees who first implemented the XMLHttpRequest interface, which was first widely deployed by the Windows Internet Explorer browser.

Special thanks also to the WHATWG for drafing a first version of this specification in their Web Applications 1.0 document.

Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)