W3C

The XMLHttpRequest Object

W3C Working Draft 05 April 2006

This version:
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
Latest version:
http://www.w3.org/TR/XMLHttpRequest
Editors:
Anne van Kesteren (Opera Software ASA) <annevk@opera.com>
Dean Jackson (W3C) <dino@w3.org>

Abstract

This specification defines the XMLHttpRequest object, an API that provides some HTTP client functionality.

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 05 April 2006 Working Draft of the XMLHttpRequest Object, the first publication of this specification. This document is produced by the Web API WG, part of the Rich Web Clients Activity in the W3C Interaction Domain. The authors of this document are the members of the W3C Web API Working Group.

Web content and browser developers are encouraged to review this draft. Please send comments to public-webapi@w3.org, the W3C's public email list for issues related to Web APIs. Archives of the list are available.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. This document is informative only. 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.

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.

Table of Contents

1. Introduction

This section is informative

The XMLHttpRequest object is 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 remove Web site.

The XMLHttpRequest object is implemented today, in some form, by many popular Web browsers. Unfortunately the implementations are not completely interoperable. The goal of this specification is to document a minimum set of interoperable features based on existing implementations, allowing Web developers to use these features without platform-specific code. In order to do this, only features that are already implemented are considered. In the case where there is a feature with no interoperable implementations, the authors have specified what they believe to be the most correct behavior.

Future versions of this specification (as opposed to future drafts of this version) may add new features, after careful examination from browser developers and Web content developers.

This specification was originally derived from the WHAT WG's Web Applications 1.0 document. The authors acknowledge the work of the WHAT WG in documenting existing behavior.

2. Conformance

This section is 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].

3. The XMLHttpRequest object

This section is normative

The following interface MAY be used to allow scripts to programmatically connect to their originating server via HTTP.

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

Example: XMLHttpRequest constructor
var r = new XMLHttpRequest();
What about non-ECMAScript implementations?

A more complete description of what can be done with XMLHttpRequest can be found in the IDL below and its associated details.

Need to define which IDL specification we are going to conform to, if any.

The XMLHttpRequest interface

interface XMLHttpRequest {

           attribute Function        onreadystatechange;
  readonly attribute unsigned short  readyState;
  void               open(in DOMString method, in DOMString uri);
  void               open(in DOMString method, in DOMString uri, in boolean async);
  void               open(in DOMString method, in DOMString uri, in boolean async, in DOMString user);
  void               open(in DOMString method, in DOMString uri, in boolean async, in DOMString user, in DOMString password);
  void               setRequestHeader(in DOMString header, in DOMString value)
                                        raises(DOMException);
  void               send(in DOMString data)
                                        raises(DOMException);
  void               send(in Document data)
                                        raises(DOMException);
  void               abort();
  DOMString          getAllResponseHeaders();
  DOMString          getResponseHeader(in DOMString header);
           attribute DOMString       responseText;
           attribute Document        responseXML;
           attribute unsigned short  status;
                                        // raises(DOMException) on retrieval
           attribute DOMString       statusText;
                                        // raises(DOMException) on retrieval
};

Attributes

onreadystatechange of type Function

An attribute that represents a function that MUST be invoked when readyState changes value. The function MAY be invoked multiple times when readyState is 3 (Receiving). Its initial value MUST be null.

What if languages don't have functions? Perhaps this should be an EventListener?
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 UA successfully completed the request, but no data has yet been received.
3 Receiving
Immediately before receiving the message body (if any). All HTTP headers have been received.
What about HEAD requests?
4 Loaded
The data transfer has been completed.
responseText of type DOMString

If the readyState attribute has a value other than 3 (Receiving) or 4 (Loaded), it MUST be the empty string. Otherwise, it MUST be the the body of the data received so far, interpreted using the character encoding specified in the response, or UTF-8 if no character encoding was specified. Invalid bytes MUST be converted to U+FFFD REPLACEMENT CHARACTER.

responseXML of type Document

If the readyState attribute has a value other than 4 (Loaded), it MUST be null. Otherwise, if 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 the document was not an XML document, or if the document could not be parsed (due to an XML well-formedness error or unsupported character encoding, for instance), it MUST be null.

status of type unsigned short

If the status attribute is not available it MUST raise an exception. It MUST be available when readyState is 3 (Receiving) or 4 (Loaded). When available, it MUST represent the HTTP status code (typically 200 for a successful connection).

Exceptions on retrieval
DOMException
INVALID_STATE_ERR SHOULD be raised if this attribute is accessed when readyState has an inappropriate value.
statusText of type DOMString

If the statusText attribute is not available it MUST raise an exception. It MUST be available when readyState is 3 (Receiving) or 4 (Loaded). When available, it MUST represent the HTTP status text sent by the server (appears after the status code).

Exceptions on retrieval
DOMException
INVALID_STATE_ERR SHOULD be raised if this attribute is accessed when readyState has an inappropriate value.

Methods

abort

When invoked, this method MUST cancels any network activity for which the object is responsible and resets the object.

No Parameters
No Return Value
No Exceptions
getAllResponseHeaders

If the readyState attribute has a value other than 3 (Receiving) or 4 (Loaded), it MUST return null. 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.

Example: Manipulating response headers
// The following script:
var r = new XMLHttpRequest();
r.open('get', 'test.txt', false);
r.send();
alert(r.getAllResponseHeaders());

// ...should display a dialog with text similar to the following:
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
No Parameters
Return Value
A single string consisting of all HTTP headers. See prose for details.
No Exceptions
getResponseHeader

If the readyState attribute has a value other than 3 (Receiving) or 4 (Loaded), it MUST return the empty string. Otherwise, it MUST represent the value of the given HTTP 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 the empty string. Header names MUST be compared case-insensitively to the method argument (header).

Example: Manipulating response headers
// The following script:
var r = new XMLHttpRequest();
r.open('get', 'test.txt', false);
r.send();
alert(r.getAllResponseHeaders());

// ...should display a dialog with text similar to the following:
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
Parameters
header of type DOMString
@XXX TDB@
Return Value
@XXX TBD@
No Exceptions
open

Calling this method MUST initialise the object by remembering the method, uri, async (defaulting to true if omitted), user (defaulting to null if omitted), and password (defaulting to null if omitted) arguments, setting the readyState attribute to 1 (Open), resetting the responseText, responseXML, status, and statusText attributes to their initial values, and resetting the list of request headers.

Same-origin security restrictions SHOULD apply.

If the URI given to this method contains a user name and a password (the latter potentially being the empty string), then these MUST be used if the user and password arguments are omitted. If the arguments are not omitted, they take precedence, even if they are null.

If open() is called when readyState is 4 (Loaded) the entire object MUST be reset.

Parameters
method of type DOMString
A valid HTTP method name. The GET, POST, and HEAD values MUST be supported.
What about PUT and DELETE?
uri of type DOMString
A URI, which MUST be resolved to an absolute URI using the script's context window.location.href value as base if available.
This does not reflect what implementations do. document.baseURI might come closer. ( ISSUE-29)
async of type boolean, optional
@XXX TBD@
user of type DOMString, optional
@XXX TBD@
password of type DOMString, optional
@XXX TBD@
No Return Value
No Exceptions
send

If the readyState attribute has a value other than 1 (Open), an exception MUST be raised. Otherwise, the readyState attribute MUST be set to 2 (Sent) and a request to uri using method method, authenticating using user and password as appropriate is sent. 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().)

If the method is POST or PUT, then the data passed to the send() method MUST be used for the entity body. If data is a string, the data MUST be encoded as UTF-8 for transmission. If the data is a Document, then the document MUST be serialised using the encoding given by data.xmlEncoding, if specified, or UTF-8 otherwise [DOM3]. If data is not a Document or a DOMString the host language MUST use the stringification mechanisms on the argument that was passed.

Implementations SHOULD support the send() to be called without the data argument to be passed.

If the response is an HTTP redirect (status code 301, 302, 303 or 307), then it MUST be transparently followed (unless it violates security or infinite loop precautions). Any other error (including a 401) MUST cause the object to use that error page as the response.

Immediately before processing the message body (if any), the readyState attribute MUST be set to to 3 (Receiving). When the request has completed loading, the readyState attribute MUST be set to 4 (Loaded).

Parameters
data of varying types (see IDL)
@XXX TDB@
No Return Value
Exceptions
DOMException
INVALID_STATE_ERR MUST be raised if this method is called when readyState has an inappropriate value.
setRequestHeader

If the readyState attribute has a value other than 1 (Open), an exception MUST be raised. If the header or value arguments contain any U+000A LINE FEED or U+000D CARRIAGE RETURN characters, or if the header argument contains any U+0020 SPACE or U+003A COLON charecters, nothing MUST be done. Otherwise, the request header header MUST be set to value. If the request header header had already been set, then the new value MUST be concatenated to the existing value using a U+002C COMMA followed by a U+0020 SPACE for separation.

Example: Setting a request header
// The following script:
var r = new XMLHttpRequest();
r.open('get', 'demo.cgi');
r.setRequestHeader('X-Test', 'one');
r.setRequestHeader('X-Test', 'two');
r.send(null);

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

User agents MUST not set any headers other than the headers set by the author using this method, with the following exceptions:

  • UAs MUST set the Host header appropriately (see open()) and not allow it to be overridden.
  • UAs MUST set the Authorization header according to the values passed to the open() method (but MUST allow calls to setRequestHeader() to append values to it).
  • UAs MAY set the Accept-Charset and Accept-Encoding headers and MUST NOT allow them to be overridden.
  • UAs MAY set the If-Modified-Since, If-None-Match, If-Range, and Range headers if the resource is cached and has not expired (as allowed by HTTP), and MUST NOT allow those headers to be overridden.
  • UAs MUST set the Connection and Keep-Alive headers as described by the HTTP specification, and MUST NOT allow those headers to be overridden.
  • UAs SHOULD set the proxy-related headers according to proxy settings of the environment, and MUST NOT allow those headers to be overridden.
  • UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it.
  • UAs SHOULD set Cookie and Cookie2 headers appropriately for the given URI and given the user's current cookies, and MUST allow authors to append values to these headers.

In particular, UAs MUST NOT automatically set the Cache-Control or Pragma headers to defeat caching [RFC2616].

Parameters
header of type DOMString
@XXX TDB@
value of type DOMString
@XXX TDB@
No Return Value
Exceptions
DOMException
UNKNOWN_ERR @XXX TDB@

HTTP requests sent from multiple different XMLHttpRequest objects in succession SHOULD be pipelined into shared HTTP connections.

A. References

This section is normative

DOM3
Document Object Model (DOM) Level 3 Core Specification, Arnaud Le Hors (IBM), Philippe Le Hégaret (W3C), Lauren Wood (SoftQuad, Inc.), Gavin Nicol (Inso EPS), Jonathan Robie (Texcel Research and Software AG), Mike Champion (Arbortext and Software AG), and Steve Byrne (JavaSoft).
RFC2119
Key words for use in RFCs to Indicate Requirement Levels, S. Bradner.
RFC2616
Hypertext Transfer Protocol -- HTTP/1.1, R. Fielding (UC Irvine), J. Gettys (Compaq/W3C), J. Mogul (Compaq), H. Frystyk (W3C/MIT), L. Masinter (Xerox), P. Leach (Microsoft), and T. Berners-Lee (W3C/MIT).

B. Authors

This section is informative

The authors of this document are the members of the W3C Web APIs Working Group.

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