W3C

XMLHttpRequest Level 2

W3C Working Draft 25 February 2008

This Version:
http://www.w3.org/TR/2008/WD-XMLHttpRequest2-20080225/
Latest Version:
http://www.w3.org/TR/XMLHttpRequest2/
Editor:
Anne van Kesteren (Opera Software ASA) <annevk@opera.com>

Abstract

XMLHttpRequest Level 2 enhances XMLHttpRequest with new features, such as cross-site requests, progress events, and the handling of byte streams for both sending and receiving.

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 First Public Working Draft of XMLHttpRequest Level 2. Please send comments to public-webapi@w3.org (archived) with [XHR2] at the start of the subject line.

In case of conflict with the editor's draft of The XMLHttpRequest Object that draft is likely to be more accurate. Please raise such differences on the public-webapi@w3.org mailing list taking into account that this draft defines a superset.

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

To be written.

2. Conformance Criteria

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

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

This specification defines a single conformance class:

Conforming user agent

A user agent must behave as described in this specification in order to be considered conformant.

User agents may optimize any algorithm given in this specification, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.

This specification uses both the terms "conforming user agent(s)" and "user agent(s)" to refer to this product class.

2.1 Dependencies

This specification relies on several underlying specifications.

Access Control for Cross-site Requests

A conforming user agent must support the algorithms of the Access Control for Cross-site Requests specification. [AC]

DOM

A conforming user agent must support some version of DOM Events and DOM Core, because this specification uses some of the features defined in those specifications. [DOM2Events] [DOM3Core]

HTML 5

This specification depends on HTML 5 for defining the Window object and how to parse a text/html resource. A conforming user agent must support these features. [HTML5]

The Window Object 1.0 draft is not referenced normatively as it appears to be no longer maintained and HTML 5 defines the Window object in more detail. This specification already depends on HTML 5 for other reasons so there is not much additional overhead because of this.

HTTP

A conforming user agent must support some version of the HTTP protocol. Requirements regarding HTTP are made throughout the specification. [RFC2616]

XML

A conforming user agent must be a conforming XML processor that reports violations of namespace well-formedness. [XML] [XMLNS]

2.2 Terminology

There is a case-insensitive match of strings s1 and s2 if after mapping the ASCII character range A-Z to the range a-z both strings are identical.

A URI is same-origin with the origin of the Document pointer if after performing scheme-based normalization on both URIs as described in section 5.3.3 of RFC 3987 the scheme, ihost and port components are identical. If either URI does not have an ihost component the URIs must not be considered same-origin. [RFC3987]

The terms origin and event handler DOM attribute are defined by the HTML 5 specification. [HTML5]

The term entity body is used as described in RFC 2616. Method token is used as described in section 5.1.1 of RFC 2616. field-name and field-value are used as described in section 4.2 of RFC 2616. [RFC2616]

The terms status return flag, uri return flag, and cross-site access request are defined by the Access Control for Cross-site Requests specification. [AC]

To dispatch a readystatechange event means that an event with the name readystatechange, with no namespace, which does not bubble and is not cancelable, and which uses the Event interface, must be dispatched at the given object.

To dispatch a progress event called e means… [PE]

2.3 Extensibility

Extensions of the API 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.

3. The XMLHttpRequest Object

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

interface XMLHttpRequestEventTarget : EventTarget {
  // event handler attributes
           attribute EventListener onabort;
           attribute EventListener onerror;
           attribute EventListener onload;
           attribute EventListener onloadstart;
           attribute EventListener onprogress;
};

interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {
  // for future use
};

interface XMLHttpRequest : XMLHttpRequestEventTarget {
  // event handler attributes
           attribute EventListener onreadystatechange;

  // ready states
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;
  readonly attribute unsigned short readyState;


  // request metadata
  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);
  
  // request
  readonly attribute XMLHttpRequestUpload upload;
  void send();
  void send(in ByteArray data);
  void send(in DOMString data);
  void send(in Document data);
  void abort();

  // response metadata
  DOMString getAllResponseHeaders();
  DOMString getResponseHeader(in DOMString header);
  readonly attribute unsigned short status;
  readonly attribute DOMString statusText;
  
  // response body
  void overrideMimeType(mime);
  readonly attribute ByteArray responseBody;
  readonly attribute DOMString responseText;
  readonly attribute Document responseXML;
};

The EventTarget interface is defined by the DOM Level 2 Events specification. [DOM2Events]

3.1 Constructor

Objects implementing the Window interface must provide the following constructor: XMLHttpRequest().

In ECMAScript this can be used as follows:

var client = new XMLHttpRequest();

When the XMLHttpRequest() constructor is invoked a persistent pointer to the associated Document object is stored on the newly created object. This is the Document pointer. The associated Document object is the one returned by the document attribute from the object on which the XMLHttpRequest() constructor was invoked (a Window object). The pointer can become "null" if the object is destroyed.

As per the conformance criteria implementations are free to implement this in any way they desire as long as the end results are identical to those given by the English prose.

If iframe is a Window object client will have a pointer to iframe.document in the following example:

var client = new iframe.XMLHttpRequest()

3.2 Event Handler Attributes

The event handler attributes listed below must be supported on objects implementing an interface that inherits from XMLHttpRequestEventTarget. Event handler attributes are event handler DOM attributes.

onabort

Must be invoked whenever an abort event is targeted at the object.

onerror

Must be invoked whenever an error event is targeted at the object.

onload

Must be invoked whenever a load event is targeted at the object.

onloadstart

Must be invoked whenever a loadstart event is targeted at the object.

onprogress

Must be invoked whenever a progress event is targeted at the object.

The following event handler attribute must be supported on objects implementing the XMLHttpRequest interface:

onreadystatechange

Must be invoked whenever a readystatechange event is targeted at the object.

3.3 Ready States

The XMLHttpRequest object can be in several states. The readyState attribute, on getting, must return the current state of the object, which must be one of the following values:

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All HTTP headers have been received. Several response members of the object are now available.

For non same-origin requests the object will never be in this state.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)

The data transfer has been completed or something went wrong during the transfer (such as infinite redirects).

The OPEN state has an associated send() flag which can be either "true" or "false". The initial value of the send() flag is "false".

The DONE state has an associated error flag which can be either "true" or "false". The initial value of the error flag is "false".

3.4 Request Metadata

This section defines the various members of the XMLHttpRequest object that can be used to initialize a network request.

When the open(method, url, async, user, password) method is invoked, the user agent must act as if it had run the following steps (unless otherwise indicated):

  1. Let stored method be the method argument.

  2. If stored method does not match the Method token raise a SYNTAX_ERR exception and terminate these steps.

  3. If stored method case-insensitively matches CONNECT, DELETE, GET, HEAD, OPTIONS POST, PUT, TRACE, or TRACK let stored method be the canonical uppercase form of the matched method name.

  4. If stored method is one of CONNECT, TRACE, or TRACK the user agent should raise a SECURITY_ERR exception and terminate these steps.

  5. Drop the fragment identifier (if any) from url and let stored url be the result of that operation.

  6. If stored url is a relative reference resolve it using the current value of the baseURI attribute of the Document pointer. If this fails raise a SYNTAX_ERR exception and terminate these steps.

  7. If stored url contains an unsupported scheme raise a NOT_SUPPORTED_ERR and terminate these steps.

  8. If the "user:password" format in the userinfo production defined in section 3.2.1 of RFC 3986 is not supported for the relevant scheme and stored url contains this format raise a SYNTAX_ERR and terminate these steps. [RFC3986]

  9. If stored url contains the "user:password" format let stored user be the user part and stored password be the password part.

  10. If stored url just contains the "user" format let stored user be the user part.

  11. The previous level of this specification raised a SECURITY_ERR at this place in case of a non same-origin stored url. This specification supports non same-origin requests and therefore this exception is no longer raised here.

  12. Let async be the value of the async argument or true if it was omitted.

  13. If the user argument was not omitted, and its syntax does not match that specified by the relevant authentication scheme, raise a SYNTAX_ERR exception and terminate these steps.

  14. If the user argument was not omitted and is not null let stored user be user encoded using the encoding specified in the relevant authentication scheme or UTF-8 if the scheme fails to specify an encoding.

    This step overrides any user that may have been set by the url argument.

  15. If the user argument was not omitted and is null remove stored user.

  16. If the password argument was not omitted and its syntax does not match that specified by the relevant authentication scheme raise a SYNTAX_ERR exception and terminate these steps.

  17. If the password argument was not omitted and is not null let stored password be password encoded using the encoding specified in the relevant authentication scheme or UTF-8 if the scheme fails to specify an encoding.

  18. If the password argument was not omitted and is null remove stored password.

  19. Abort the send() algorithm, set response entity body to "null" and reset the list of request headers.

  20. The user agent should cancel any network activity for which the object is responsible.

  21. Switch the object to the OPENED state, set the send() flag to "false" and then synchronously dispatch a readystatechange event on the object and return the method call.

Each request has a list of request headers with associated values. The setRequestHeader(header, value) method can be used to manipulate those values and set new request headers. When invoked, the user agent must act as if it had run the steps below (unless otherwise indicated).

There should be a note here explaining restrictiosn on headers for non same-origin requests, but those rules haven't been decided upon just yet.

  1. If the state of the object is not OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

  2. If the send() flag is "true" raise an INVALID_STATE_ERR exception and terminate these steps.

  3. If the header argument does not match the field-name production or is null raise a SYNTAX_ERR exception and terminate these steps.

  4. If the value argument is null terminate these steps. (Do not raise an exception.)

  5. If the value argument does not match the field-value production raise a SYNTAX_ERR and terminate these steps.

  6. For security reasons, these steps should be terminated if the header argument case-insensitively matches one of the following headers:

  7. Also for security reasons, these steps should be terminated if the start of the header argument case-insensitively matches Proxy- or Sec-.

  8. If the header argument is not in the list of request headers append the header with its associated value to the list and terminate these steps.

  9. If the header argument is in the list of request headers 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');
client.send();

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

3.5 Request

3.5.1 Tracking Upload Progress

To track the progress of data being uploaded through the send() method the XMLHttpRequest object offers an upload attribute. On getting, this attribute must return an object implementing the XMLHttpRequestUpload interface. This object can be used to register event listeners on which will be triggered during the upload process.

3.5.2 Request Variables and Algorithms

The same-origin flag indicates whether the current being performed is same-origin or not. A value of "true" indicates it is and "false" indicates it is not.

The current request URI is initially stored url (as set by the open() method) and is updated as described in the send() algorithm.

The upload complete flag indicates is used in several algorithms to determine whether or not to dispatch an event. The initial value of the flag is "false".

When the steps for the send() method say something is a network error the user agent must act as if the following steps had been run:

  1. Set the response entity body to "null", the error flag to "true" and reset the list of request headers.

  2. Synchronously switch the state to DONE.

  3. If async is set to false raise a NETWORK_ERR exception and terminate the overall algorithm.

  4. Synchronously dispatch a readystatechange event on the object.

  5. Synchronously dispatch a progress event called error on the object.

  6. If the upload complete flag is "false" set the flag to "true" and synchronously dispatch a progress event called error on the object returned by the upload attribute.

  7. Terminate the overall algorithm.

When the steps for the send() method say something is an abort error the user agent must act as if the following steps had been run:

  1. Set the response entity body to "null", the error flag to "true" and reset the list of request headers.

  2. Synchronously switch the state to DONE.

  3. If async is set to false raise an ABORT_ERR exception and terminate the overall algorithm.

  4. Synchronously dispatch a readystatechange event on the object.

  5. Synchronously dispatch a progress event called abort on the object.

  6. If the upload complete flag is "false" set the flag to "true" and synchronously dispatch a progress event called abort on the object returned by the upload attribute.

  7. Terminate the overall algorithm.

When the steps for the send() method say to switch to the LOADING state the user agent must act as if the following steps had been run:

  1. Synchronously switch the state to LOADING.

  2. Synchronously dispatch a readystatechange event on the object.

When the steps for the send() method say to make progress notifications user agents must, while the download is progressing and async is true, synchronously dispatch a progress event called progress at the object every 350ms (±200ms) or for every byte received, whichever is least frequent.

When the s teps for the send() method say to make upload progress notifications user agents must, if the request entity body is not empty and async is true follow the following rules:

3.5.3 Initiating a Request

The send(data) method initiates the request and its optional argument provides the entity body for the request. Authors are encouraged to ensure that they have specified the Content-Type header via setRequestHeader() before invoking send() with a non-null data argument.

When invoked, the user agent must act as if it had run the following steps (unless otherwise noted). Note that this algorithm might get aborted if the open() or abort() method is invoked. When the send() algorithm is aborted the user agent must terminate the algorithm after finishing the step it is on.

The following algorithm can not be aborted through script when async is false. It can only be aborted when async is true and only after the method call has returned.

  1. If the state of the object is not OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

  2. If the send() flag is "true" raise an INVALID_STATE_ERR exception and terminate these steps.

  3. If async is true set the send() flag to "true".

  4. Synchronously dispatch a readystatechange event on the object.

    The state of the object does not change. The event is dispatched for historical reasons.

  5. If the data argument has not been omitted and is not null use it for the entity body observing the following rules:

    data is a ByteArray

    Use data literally for transmission.

    data is a DOMString

    Encode data using UTF-8 for transmission.

    data is a Document

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

    If no Content-Type header is in the list of request headers append a Content-Type header to the list of request headers with a value of application/xml.

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

    Anything else

    Use the stringification mechanisms of the host language on data and treat the result as if data is a DOMString. Or, if this fails, act as if data is null.

    If the data argument has been omitted, or is null, no entity body is used in the request.

  6. If async is true synchronously dispatch a progress event called loadstart on the object.

  7. If async is true and the request entity body is not empty dispatch a progress event called loadstart on the object returned by the upload attribute.

  8. If async is true return the send() method call. (Do not terminate the steps in the algorithm though.)

  9. If the current request URI is same-origin this is a same-origin request. Make a request to the current request URI using HTTP method stored method, user stored user (if provided), password stored password (if provided), taking into account the entity body, list of request headers and the rules listed directly after this set of steps. Make progress notifications, make upload progress notifications, and follow the list of request rules:

    If the response is an HTTP redirect

    If the redirect violates security or infinite loop precautions or the scheme is not supported this is a network error.

    Otherwise, run the following set of steps:

    1. Set the current request URI to the new location.

    2. If the current request URI is same-origin follow the redirect while observing the request rules for same-origin requests.

    3. Otherwise, follow the steps for a non same-origin request terminating this one.

    HTTP places requirements on the user agent 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.

    If the user cancels the download

    This is an abort error.

    If there is a network error

    In case of DNS errors, or other type of network errors, this is a network error. This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.

    Once all HTTP headers have been received

    If all HTTP headers have been received, before receiving the message body (if any) run the following steps:

    1. Synchronously switch the state to HEADERS_RECEIVED.

    2. Synchronously dispatch a readystatechange event on the object.

    Once the first byte (or more) of the response entity body has been received
    If there is no response entity body

    Switch to the LOADING state and once the complete resource has been downloaded go to the next step.

    Otherwise, if it is non same-origin this is a non same-origin request. Set the same-origin flag to "false", then make a cross-site access request, using HTTP method stored method, taking into account the entity body if stored method is not GET, and handle the return values as indicated below.

    "Cross-site access request" will likely take a list of methods in due course as headers in cross-site requests require a careful policy.

    The stored user and stored password variables are always ignored as part of a non same-origin request as including them would allow a site to perform a distributed password search.

    status return flag is "same-origin"

    Set the current request URI to the value of the uri return flag, set the same-origin flag to "true", and then make a same-origin request.

    status return flag is "network"

    This is a network error.

    status return flag is "abort"

    This is an abort error.

    status return flag is "success"

    Make progress notifications, switch to the LOADING state and once the resource has been downloaded completely go to the next step.

  10. When the request has successfully completed loading, run the following steps:

    1. Synchronously switch the state to DONE.

    2. Synchronously dispatch a readystatechange event on the object.

    3. Synchronously dispatch a progress event called load on the object.

    4. If async is false return the method call.

If the user agent allows the user to configure 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 Unauthorized requests appropriately. If authentication fails, user agents should prompt the users for credentials. [RFC2617]

If the user agent supports HTTP State Management 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 behavior (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. The user agent 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-Encoding and Accept-Charset headers as appropriate; it must not automatically set the Accept. If the Accept-Language header is not set using setRequestHeader() user agents should provide it. Responses to such requests must have the content-encodings automatically decoded. [RFC2616]

3.5.4 Aborting a Request

When the abort() method is invoked, the user agent must act as if it had run the following steps (unless otherwise noted):

  1. Abort the send() algorithm, set the response entity body to "null", the error flag to "true" and remove any registered request headers.

  2. The user agent should cancel any network activity for which the object is responsible.

  3. If the state is UNSENT, OPENED and the send() flag is "false", or DONE go to the next step.

    Otherwise, switch the state to DONE, set the send() flag to "false" and synchronously dispatch a readystatechange event on the object.

  4. Switch the state to UNSENT. (Do not dispatch a readystatechange event.)

  5. Synchronously dispatch a progress event called abort on the object.

  6. If the upload complete flag is "false" set the flag to "true" and synchronously dispatch a progress event called abort on the object returned by the upload attribute.

3.6 Response Metadata

The getAllResponseHeaders() method provides access to all response headers as a single string. When invoked, the user agent must act as if it had run the following steps:

  1. If the state is UNSENT or OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

  2. If the error flag is "true" or the same-origin flag is "false" return null and terminate these steps.

  3. Return all the HTTP headers, as a single string, with each header line separated by a U+000D CR U+000A LF pair excluding the status line.

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

// ...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

The getResponseHeader(header) method returns the value of a response header given by the header argument. When invoked, the user agent must act as if it had run the following steps:

  1. If the state is UNSENT or OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

  2. If the error flag is "true" return null and terminate these steps.

  3. If the same-origin flag is "false" and the header argument does not case-insensitively matches Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, or Pragma return null and terminate these steps.

  4. If the header argument does not match the field-name production raise a SYNTAX_ERR exception and terminate these steps.

  5. If the header argument case-insensitively matches multiple HTTP headers for the last request sent, return the values of these headers as a single concatenated string separated from each other by an U+002C COMMA followed by an U+0020 SPACE and terminate these steps.

  6. If the header argument case-insensitively matches a single HTTP header for the last request sent return the value of that header and terminate these steps.

  7. Return null.

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

// ...should output something similar to the following text:
Content-Type: text/plain; charset=utf-8

The status attribute, on getting and if available, must return the HTTP status code sent by the server (typically 200 for a successful request). If not available, the user agent must raise an INVALID_STATE_ERR exception.

The statusText attribute, on getting and if available, must return the HTTP status text sent by the server (appears after the status code). If not available, the user agent must raise an INVALID_STATE_ERR exception.

3.7 Response Body

The following subsection defines various variables and algorithms important to the response body. The subsection after that defines the members of the XMLHttpRequest object relevant to the response body.

3.7.1 Definitions

The response MIME type is the MIME type the Content-Type header contains without any parameters or "null" if the header could not be parsed properly or was omitted. The override MIME type is initially "null" and can get a value if overrideMimeType() is invoked. Final MIME type is the override MIME type unless that is "null" in which case it is the response MIME type.

The response charset is the value of the charset parameter of the Content-Type header or null if there was no charset parameter or if the header could not be parsed properly or was omitted. The override charset is initially "null" and can get a value if overrideMimeType() is invoked. Final charset is the override charset unless that is "null" in which case it is the response charset.

The response entity body is the fragment of the entity body received so far (LOADING state) or the complete entity body (DONE state). If there is no entity body the response entity body is "null".

The text response entity body is either a DOMString representing the response entity body or null. The text response entity body is the return value of the following algorithm:

  1. If the response entity body is "null" return null and terminate these steps.

  2. Let charset be the final charset.

  3. Let mime be the final MIME type.

  4. If charset is "null" and mime is "null", text/xml, application/xml or ends in +xml use the rules set forth in the XML specifications to determine the character encoding. Let charset be the determined character encoding.

  5. If charset is "null" and mime is text/html follow the rules set forth in the HTML specification to determine the character encoding. Let charset be the determined character encoding. [HTML5]

  6. If charset is "null" then, for each of the rows in the following table, starting with the first one and going down, if the first bytes of bytes match the bytes given in the first column, then let charset be the encoding given in the cell in the second column of that row. If there is no match charset remains "null".

    Bytes in Hexadecimal Description
    00 00 FE FF UTF-32BE BOM
    FF FE 00 00 UTF-32LE BOM
    FE FF UTF-16BE BOM
    FF FE UTF-16LE BOM
    EF BB BF UTF-8 BOM
  7. If charset is "null" let charset be UTF-8.

  8. Return the result of decoding the response entity body using charset. Or, if that fails, return null.

The document response entity body is either a Document representing the response entity body or null. The document response entity body is the return value of the following algorithm:

  1. If the response entity body is "null" terminate these steps and return null.

  2. If final MIME type is text/html return an object implementing the Document interface that represents the response entity body parsed following the rules set forth in the HTML specification for an HTML parser with scripting disabled and then terminate this algorithm. [HTML5]

  3. If final MIME type is not "null", not text/xml, not application/xml and does not end in +xml terminate these steps and return null.

  4. Parse the response entity body into a document tree following the rules from the XML specifications. Let the result be parsed document. If this fails (unsupported character encoding, namespace well-formedness error et cetera) terminate these steps return null. [XML] [XMLNS]

    Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.

  5. Let document be an object implementing the Document interface representing the parsed document.

  6. If the same-origin flag is "false" ensure that the cookie attribute of document returns the empty string on getting.

  7. Return document.

3.7.2 Response Body Members

When the overrideMimeType(mime) method is invoked, the user agent must act as if it had run the following steps:

  1. If parsing mime analogously to the value of the Content-Type headers fails raise a SYNTAX_ERR exception and abort this algorithm.

  2. If a MIME type (without any parameters) is successfully parsed set override MIME type to that MIME type.

  3. If a charset parameter is successfully parsed set override charset to its value.

The responseBody attribute, on getting, must return the result of running the following steps:

  1. If the state is not LOADING or DONE raise an INVALID_STATE_ERR exception and terminate these steps.

  2. Return a ByteArray object representing the response entity body or return null if the response entity body is "null".

The responseText attribute, on getting, must return the result of running the following steps:

  1. If the state is not LOADING or DONE raise an INVALID_STATE_ERR exception and terminate these steps.

  2. Return the text response entity body.

The responseXML attribute, on getting, must return the result of running the following steps:

  1. If the state is not DONE raise an INVALID_STATE_ERR exception and terminate these steps.

  2. Return the document response entity body.

The responseXML attribute has XML in its name for historical reasons. It also returns documents created using an HTML parser.

3.8 Events summary

The following events are dispatched on XMLHttpRequest and/or XMLHttpRequestUpload objects:

Event name Interface Dispatched when…
abort ProgressEvent When the request has been aborted. For instance, by invoking the abort() method.
error ProgressEvent When the request has failed.
load ProgressEvent When the request has successfully completed.
loadstart ProgressEvent When the request starts.
progress ProgressEvent While loading and sending data.
readystatechange Event The readyState attribute changes and at some seemingly arbitrary times for historical reasons.

3.9 Exceptions

Several algorithms in this specification may result in an exception being thrown. These exceptions are all part of the group ExceptionCode and use the DOMException object which is defined in DOM Level 3 Core. In addition this specification extends the ExceptionCode group with several new constants as indicated below. [DOM3Core]

const unsigned short SECURITY_ERR = 18;
const unsigned short NETWORK_ERR = 101;
const unsigned short ABORT_ERR = 102;

The SECURITY_ERR exception is raised if an attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.

The SECURITY_ERR exception is expected to be eventually folded into an update of the the DOM Level 3 Core specification with an equivalent definition and identical constant value. Until that happens it is defined here to guide implementors. (This is also the reason it has a different constant value from the other exceptions.)

The NETWORK_ERR exception is raised when a network error occurs in synchronous requests.

The ABORT_ERR exception is raised when the user aborts a request in synchronous requests.

References

[AC]
Access Control for Cross-site Requests (work in progress), A. van Kesteren, editor. W3C, February 2008.
[DOM2Events]
Document Object Model (DOM) Level 2 Events Specification, T. Pixley, editor. W3C, November 2000.
[DOM3Core]
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. W3C, April 2004.
[ECMAScript]
ECMAScript Language Specification, Third Edition. ECMA, December 1999.
[HTML5]
HTML 5 (work in pgoress), I. Hickson, D. Hyatt, editors. W3C, 2008.
HTML 5 (work in progress), I. Hickson, editor. WHATWG, 2008.
[PE]
Progress Events 1.0 (work in progress), C. McCathieNeville, editor. W3C, 2007.
[RFC2046]
Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein, editors. IETF, November 1996.
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels, S. Bradner. IETF, March 1997.
[RFC2616]
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.
[RFC2617]
HTTP Authentication: Basic and Digest Access Authentication, P. Hallam-Baker, J. Hostetler, S. Lawrence, P. Leach, A. Luotonen, L. Stewart, editors. IETF, June 1999.
[RFC2965]
HTTP State Management Mechanism, D. Kristol, L. Montulli, editors. IETF, October 2000.
[RFC3986]
Uniform Resource Identifier (URI): Generic Syntax, T. Berners-Lee, R. Fielding, L. Masinter, editors. IETF, January 2005.
[XML]
Extensible Markup Language (XML) 1.0 (Fourth Edition), T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau, editors. W3C, September 2006.
[XMLNS]
Namespaces in XML (Second Edition), T. Bray, D. Hollander, A. Layman, R. Tobin, editors. W3C, August 2006.

Acknowledgments

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

The editor would like to thank Alexey Proskuryakov, David Andersson, Ian Hickson, Jonas Sicking, Maciej Stachowiak, Mohamed Zergaoui and Rune Halvorsen for their contributions to this specification.

Special thanks also to all who have contributed to The XMLHttpRequest Object specification.

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