To the extent possible under law, the editor has waived all copyright and
related or neighboring rights to this work. In addition, as of
22 May 2013, the editor has made this specification available
under the
Open Web Foundation Agreement Version 1.0,
which is available at
http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0.
The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.
XMLHttpRequest
status attributestatusText attributegetResponseHeader() methodgetAllResponseHeaders() methodoverrideMimeType() methodresponseType attributeresponse attributeresponseText attributeresponseXML attributeFormDataProgressEvent
data: URLs and HTTPThis section is non-normative.
The XMLHttpRequest object is an API for
fetching resources.
The name XMLHttpRequest is historical and has no baring on its
functionality.
Some simple code to do something with data from an XML document fetched over the network:
function processData(data) {
// taking care of data
}
function handler() {
if(this.readyState == this.DONE) {
if(this.status == 200 &&
this.responseXML != null &&
this.responseXML.getElementById('test').textContent) {
// success!
processData(this.responseXML.getElementById('test').textContent);
return;
}
// something went wrong
processData(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
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 == this.DONE)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}
The XMLHttpRequest object was initially defined as part of
the WHATWG's HTML effort. (Long after Microsoft shipped an implementation.)
It moved to the W3C in 2006. Extensions (e.g. progress events and
cross-origin requests) to XMLHttpRequest were developed in a
separate draft (XMLHttpRequest Level 2) until end of 2011, at which point
the two drafts were merged and XMLHttpRequest became a single
entity again from a standards perspective. End of 2012 it moved back to the
WHATWG.
Historical discussion can be found in the following mailing list archives:
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this specification are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
User agents, Working Groups, and other interested parties are strongly encouraged to discuss new features with the WHATWG community.
This specification heavily borrows terminology, from Cross-Origin Resource Sharing, DOM, DOM Parsing and Serialization, Encoding, File API, HTML, HTTP, Typed Array, URL, Web IDL, and XML. [CORS] [DOM] [DOMPS] [ENCODING] [FILEAPI] [HTML] [HTTP] [TYPEDARRAY] [URL] [WEBIDL] [XML] [XMLNS]
The term user credentials for the purposes of this
specification means cookies, HTTP authentication, and client-side SSL
certificates. Specifically it does not refer to proxy authentication or the
Origin header.
[COOKIES]
XMLHttpRequest[NoInterfaceObject]
interface XMLHttpRequestEventTarget : EventTarget {
// event handlers
attribute EventHandler onloadstart;
attribute EventHandler onprogress;
attribute EventHandler onabort;
attribute EventHandler onerror;
attribute EventHandler onload;
attribute EventHandler ontimeout;
attribute EventHandler onloadend;
};
interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {
};
enum XMLHttpRequestResponseType {
"",
"arraybuffer",
"blob",
"document",
"json",
"text"
};
dictionary XMLHttpRequestOptions {
boolean anonymous = false;
};
[Constructor(optional XMLHttpRequestOptions options)]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
// event handler
attribute EventHandler onreadystatechange;
// 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
void open(ByteString method, DOMString url, optional boolean async = true, optional DOMString? username = null, optional DOMString? password = null);
void setRequestHeader(ByteString header, ByteString value);
attribute unsigned long timeout;
attribute boolean withCredentials;
readonly attribute XMLHttpRequestUpload upload;
void send(optional (ArrayBufferView or Blob or Document or DOMString or FormData)? data = null);
void abort();
// response
readonly attribute unsigned short status;
readonly attribute ByteString statusText;
ByteString? getResponseHeader(ByteString header);
ByteString getAllResponseHeaders();
void overrideMimeType(DOMString mime);
attribute XMLHttpRequestResponseType responseType;
readonly attribute any response;
readonly attribute DOMString responseText;
readonly attribute Document? responseXML;
};
Each XMLHttpRequest object has a unique, associated
XMLHttpRequestUpload object.
Each XMLHttpRequest object has its own
task source. Namely, the
XMLHttpRequest task source.
The XMLHttpRequest object has an associated
anonymous flag. If the anonymous flag is set,
user credentials and the
source origin are not exposed when
fetching resources.
When the JavaScript global environment
is a document environment, the
XMLHttpRequest object has an associated
document.
client = new XMLHttpRequest()
XMLHttpRequest object.
client = new XMLHttpRequest({anonymous:true})
XMLHttpRequest object that has its
anonymous flag set.
The
XMLHttpRequest(options)
constructor must run these steps:
Let xhr be a new XMLHttpRequest
object.
If options's anonymous member is
true, set xhr's anonymous flag.
If the JavaScript global environment is a document environment, set document to the document associated with the global object of xhr's interface object.
Return xhr.
An XMLHttpRequest object must not be garbage collected if
its state is OPENED and the
send() flag is set, its state is
HEADERS_RECEIVED, or
its state is LOADING, and
one of the following is true:
It has one or more
event listeners
registered whose type is
readystatechange,
progress,
abort,
error,
load,
timeout, or
loadend.
The upload complete flag is unset and the associated
XMLHttpRequestUpload object has one or more
event listeners
registered whose type is
progress,
abort,
error,
load,
timeout, or
loadend.
If an XMLHttpRequest object is garbage collected while its
connection is still open, the user agent must cancel any instance of the
fetch algorithm opened by this object,
discarding any tasks
queued for them, and
discarding any further data received from the network for them.
The following are the
event handlers (and their corresponding
event handler event types)
that must be supported on objects implementing an interface that inherits
from XMLHttpRequestEventTarget as attributes:
| event handler | event handler event type |
|---|---|
onloadstart
| loadstart
|
onprogress
| progress
|
onabort
| abort
|
onerror
| error
|
onload
| load
|
ontimeout
| timeout
|
onloadend
| loadend
|
The following is the
event handler
(and its corresponding
event handler event type) that must be
supported as attribute solely by the
XMLHttpRequest object:
| event handler | event handler event type |
|---|---|
onreadystatechange
| readystatechange |
client . readyState
Returns the current state.
The XMLHttpRequest object can be in several states. The
readyState
attribute must return the current state, 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 redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
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 (e.g. infinite redirects).
The send() flag indicates
that the send() method has
been invoked. It is initially unset and is used during the
OPENED state.
The error flag indicates some type of network error or fetch termination. It is initially unset.
Each XMLHttpRequest object has the following
request-associated concepts:
request method,
request URL,
author request headers,
request entity body,
source origin,
referrer source,
synchronous flag,
upload complete flag, and
upload events flag.
The author request headers is a list of HTTP header names and corresponding header values. Comparisons against the HTTP header names must be done in a case-insensitive manner. Initially it must be empty.
The request entity body must initially be null.
The synchronous flag, upload complete flag, and upload events flag must be initially unset.
open() methodclient . open(method, url [, async = true [, username = null [, password = null]]])
Sets the request method, request URL, and synchronous flag.
Throws a "SyntaxError" exception if
either method is not a valid HTTP method or
url cannot be parsed.
Throws a "SecurityError" exception
if method is a case-insensitive match for
CONNECT, TRACE or TRACK.
Throws an "InvalidAccessError"
exception if async is false, the
JavaScript global environment is a
document environment, and either the
anonymous flag is set, the
timeout attribute is not
zero, the
withCredentials
attribute is true, or the
responseType
attribute is not the empty string.
The
open(method, url, async, username, password)
method must run these steps (unless otherwise indicated):
Let base be null.
If the JavaScript global environment is a document environment, run these steps:
If document is not
fully active,
throw an
"InvalidStateError" exception.
Set base to the document base URL of document.
Set source origin to a globally unique identifier if the anonymous flag is set, and the origin of document otherwise.
Set referrer source to document.
If the JavaScript global environment is a worker environment, run these steps:
Set base to the script's base URL.
Set source origin to the script's origin.
Set referrer source to the script's referrer source.
If method does not match the Method
token production, throw a
"SyntaxError" exception.
If method is a case-insensitive match for CONNECT,
DELETE, GET, HEAD, OPTIONS,
POST, PUT, TRACE, or TRACK, subtract
0x20 from each byte in the range 0x61 (ASCII a) to 0x7A (ASCII z).
If it does not match any of the above, it is passed through literally, including in the final request.
If method is a case-sensitive match for CONNECT,
TRACE, or TRACK,
throw a
"SecurityError" exception.
Allowing these methods would pose a security risk. [HTTPVERBSEC]
Let parsed URL be the result of parsing url with base.
If parsed URL is failure,
throw a
"SyntaxError" exception.
If parsed URL's relative flag is set, run these substeps:
If async is false, the
JavaScript global environment is a
document environment, and either the
anonymous flag is set, the
timeout attribute value is not zero, the
withCredentials attribute value is
true, or the responseType attribute
value is not the empty string,
throw an
"InvalidAccessError" exception.
Set the error flag.
This is meaningless unless the
send() algorithm is running.
The user agent should cancel any network activity for which the object is responsible.
If there are any tasks from
the object's XMLHttpRequest task source in one of the
task queues, then remove them.
Set variables associated with the object as follows:
Set request method to method.
Set request URL to parsed URL.
If async is false, set the synchronous flag.
Set author request headers to the empty list.
Unset the send() flag.
Set response entity body to null.
If the state is not OPENED, run these substeps:
Change the state to OPENED.
Fire an event named readystatechange.
setRequestHeader() methodclient . setRequestHeader(header, value)
Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value.
Throws an "InvalidStateError"
exception if the state is not
OPENED or if the
send() flag is set.
Throws a "SyntaxError" exception if
header is not a valid HTTP header field name or if
value is not a valid HTTP header field value.
As indicated in the algorithm below certain headers cannot
be set and are left up to the user agent. In addition there are certain
other headers the user agent will take control of if they are not set by
the author as indicated at the end of the
send() method section.
For non same origin requests using the HTTP
GET method a preflight request is made when headers other
than Accept and Accept-Language are set.
The
setRequestHeader(header, value)
method must run these steps:
If the state is not OPENED,
throw an
"InvalidStateError" exception.
If the send() flag is set,
throw an
"InvalidStateError" exception.
If header does not match the
field-name production,
throw a
"SyntaxError" exception.
If value does not match the
field-value production,
throw a
"SyntaxError" exception.
An empty string represents an empty header field value.
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
… or if the start of header is a case-insensitive
match for Proxy- or Sec- (including when
header is just Proxy- or Sec-).
The above headers are controlled by the user agent to
let it control those aspects of transport. This guarantees data
integrity to some extent. Header names starting with Sec-
are not allowed to be set to allow new headers to be minted that are
guaranteed not to come from XMLHttpRequest.
If header is not in the author request headers list, append header with its associated value to the list and terminate these steps.
If header is in the author request headers list, append
",", followed by U+0020, followed by value, to the
value of the header matching header.
The XMLHttpRequest standard intentionally constraints the use of HTTP here in line with contemporary implementations.
Some simple code demonstrating what happens when setting the same header twice:
// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'demo.cgi');
client.setRequestHeader('X-Test', 'one');
client.setRequestHeader('X-Test', 'two');
client.send();
// …results in the following header being sent:
X-Test: one, two
timeout attributeclient . timeout
Can be set to a time in milliseconds. When set to a non-zero value
will cause fetching to
terminate after the given time has passed. When the time has passed, if
the synchronous flag is unset, a
timeout event will then be
dispatched,
or a "TimeoutError" exception will be
thrown otherwise
(for the send() method).
When set: throws an
"InvalidAccessError" exception if
the synchronous flag is set and the
JavaScript global environment is a
document environment.
The
timeout
attribute must return its value. Initially its value must be zero.
Setting the timeout
attribute must run these steps:
If the
JavaScript global environment is a
document environment and the
synchronous flag is set,
throw an
"InvalidAccessError" exception.
Set its value to the new value.
This implies that the
timeout attribute can be
set while fetching is in
progress. If that occurs it will still be measured relative to the start
of fetching.
withCredentials attributeclient . withCredentials
True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.
When set: throws an
"InvalidStateError" exception if the
state is not UNSENT or
OPENED, or if
the send() flag is set.
When set: throws an
"InvalidAccessError" exception if
either the synchronous flag is set and the
JavaScript global environment is a
document environment or if the
anonymous flag is set.
The
withCredentials
attribute must return its value. Initially its value must be false.
Setting the
withCredentials
attribute must run these steps:
If the state is not UNSENT or
OPENED,
throw an
"InvalidStateError" exception.
If the send() flag is set,
throw an
"InvalidStateError" exception.
If the anonymous flag is set,
throw an
"InvalidAccessError" exception.
If the
JavaScript global environment is a
document environment and the
synchronous flag is set,
throw an
"InvalidAccessError" exception.
Set the withCredentials
attribute's value to the given value.
The withCredentials
attribute has no effect when fetching
same-origin resources.
upload attributeclient . upload
Returns the associated XMLHttpRequestUpload
object. It can be used to gather transmission information when data is
transferred to a server.
The
upload
attribute must return the associated
XMLHttpRequestUpload object.
As indicated earlier, each XMLHttpRequest
object has an associated XMLHttpRequestUpload object.
send() methodclient . send([data = null])
Initiates the request. The optional argument provides the
request entity body. The argument is ignored if
request method is GET or
HEAD.
Throws an "InvalidStateError"
exception if the state is not
OPENED or if the
send() flag is set.
The send(data)
method must run these steps (unless otherwise noted):
If the state is not OPENED,
throw an
"InvalidStateError" exception.
If the send() flag is set,
throw an
"InvalidStateError" exception.
If the request method is GET or
HEAD, set data to null.
If data is null, do not include a request entity body and go to the next step.
Otherwise, let encoding be null, mime type be null, and then follow these rules, depending on data:
ArrayBufferView
Let the request entity body be the raw data represented by data.
Blob
If the object's type attribute value is not
the empty string, let mime type be its value.
See also Blob's
type attribute.
Let the request entity body be the raw data represented by data.
Let encoding be the encoding of data. If encoding is utf-16le or utf-16be, set encoding to utf-8.
If data is an
HTML document, let
mime type be "text/html", or let
mime type be "application/xml" otherwise. Then
append ";charset=encoding" to
mime type.
Serialize data, and let the request entity body be the result, converted to Unicode and encoded using encoding encoding. Re-throw any exception this throws.
Should we only encode as utf-8? What happens in the face of an encoder error?
In particular, if the document cannot be serialized an
"InvalidStateError" exception is
thrown.
Subsequent changes to the document have no effect on what is transferred.
Let encoding be "UTF-8".
Let mime type be "text/plain;charset=UTF-8".
Let the request entity body be data converted to Unicode and encoded as utf-8.
FormData
Let the request entity body be the result of running
the
multipart/form-data encoding algorithm
with data as form data set and with
utf-8 as the
explicit character encoding.
Let mime type be the concatenation of
"multipart/form-data;",
a U+0020 SPACE character,
"boundary=", and the
multipart/form-data boundary string
generated by the
multipart/form-data encoding algorithm.
If a Content-Type header is in
author request headers and its value is a
valid MIME type that has a
charset parameter whose value is not a case-insensitive
match for encoding, and encoding
is not null, set all the charset parameters of that
Content-Type header to encoding.
If no Content-Type header is in
author request headers and mime type is
not null, append a Content-Type header with value
mime type to author request headers.
If the synchronous flag is set, release the storage mutex.
Unset the error flag, upload complete flag and upload events flag.
If there is no request entity body or if it is empty, set the upload complete flag.
If the synchronous flag is unset and one or more
event listeners are registered on the XMLHttpRequestUpload
object, set the upload events flag.
If the synchronous flag is unset, run these substeps:
Set the send() flag.
Fire a progress event named loadstart.
If the upload complete flag is unset,
fire a progress event named loadstart
on the XMLHttpRequestUpload object.
Return the send()
method call, but continue running the steps in this algorithm.
scheme is
"data"
These are the same-origin request steps.
Fetch the request URL from origin source origin, using referrer source as override referrer source, with the synchronous flag set if the synchronous flag is set, using HTTP method request method, taking into account the request entity body, list of author request headers, and the rules listed at the end of this section.
While making the request also follow the same-origin request event rules.
The
send() method call will
now be returned by virtue of this algorithm ending.
Make upload progress notifications.
While processing the request, as data becomes available and when the user interferes with the request, queue tasks to update the response entity body and follow the same-origin request event rules.
These are the cross-origin request steps.
Make a cross-origin request, passing these as parameters:
about:blank", and the
referrer source otherwise.
withCredentials
attribute's value is false.
While making the request also follow the cross-origin request event rules.
The
send() method call will
now be returned by virtue of this algorithm ending.
While processing the request, as data becomes available and when the end user interferes with the request, queue tasks to update the response entity body and follow the cross-origin request event rules.
If the user agent supports HTTP Authentication and
Authorization is not in the list
of author request headers, it should
consider requests originating from the XMLHttpRequest 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,
source origin and the
request URL are same origin,
Authorization is not in the list
of author request headers,
request URL's
username is
the empty string and request URL's
password is
null, user agents should prompt the end user for their username and
password.
Otherwise, if authentication fails, user agents must not prompt the end user for their username and password. [HTTPAUTH]
Unfortunately end users are prompted because of legacy content constraints. However, when possible this behavior is prohibited, as it is bad UI. E.g. that is why the same origin restriction is made above.
If the user agent implements a HTTP cache it should
respect Cache-Control headers in
author request headers
(e.g. Cache-Control: no-cache bypasses the cache). It
must not send Cache-Control or
Pragma request headers automatically unless the end user
explicitly requests such behavior (e.g. by reloading the page).
For 304 Not Modified responses that are a result of a
user agent generated conditional request the user agent
must act as if the server gave a 200 OK
response with the appropriate content. The user agent
must allow author request headers to override automatic cache
validation (e.g. If-None-Match or
If-Modified-Since), in which case
304 Not Modified responses must be passed through.
[HTTP]
If the user agent implements server-driven content-negotiation
it must follow these constraints for the
Accept and Accept-Language request headers:
Both headers must not be modified if they are in author request headers.
If not in author request headers,
Accept-Language with an appropriate value should be appended
to it.
If not in author request headers, Accept
with value */* must be appended to it.
Responses must have the content-encodings automatically decoded. [HTTP]
Besides the author request headers, user agents
should not include additional request headers other than those mentioned
above or other than those authors are not allowed to set using
setRequestHeader().
This ensures that authors have a predictable API.
send() methodThe same-origin request event rules are as follows:
Terminate these steps.
If the redirect violates infinite loop precautions this is a network error.
Otherwise, run these steps:
Set the request URL to the
URL conveyed by the
Location header.
If the source origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.
Otherwise, follow the cross-origin request steps and terminate the steps for this algorithm.
HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end users to be notified of certain kinds of automatic redirections.
This is an abort error.
In case of DNS errors, TLS negotiation failure, or other type of network errors, this is a network error. Do not request any kind of end user interaction.
This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.
timeout is not 0
and since the request started the amount of milliseconds specified by
timeout has passedThis is a timeout error.
The cross-origin request event rules are as follows:
Terminate these steps.
This is a network error.
This is an abort error.
timeout is not 0
and since the request started the amount of milliseconds specified by
timeout has passedThis is a timeout error.
When something is said to be a network error run the
request error steps for exception
"NetworkError" and
event error.
When something is said to be an abort error run the
request error steps for exception
"AbortError" and event
abort.
When something is said to be an timeout error run the
request error steps for exception
"TimeoutError" and event
timeout.
When something is said to be a request error for exception exception and event event run these steps:
The user agent should cancel any network activity for which the object is responsible.
If there are any
tasks from the
object's XMLHttpRequest task source in one of
the task queues,
then remove them.
Set the the error flag.
Change the state to DONE.
If the synchronous flag is set, throw an exception exception.
Fire an event named readystatechange.
At this point it is clear that the synchronous flag is unset.
If the upload complete flag is unset, follow these substeps:
Set the upload complete flag.
Fire a progress event named
progress on the XMLHttpRequestUpload object.
Fire a progress event named
event on the XMLHttpRequestUpload object.
Fire a progress event named
loadend on the XMLHttpRequestUpload object.
Fire a progress event named progress.
Fire a progress event named event.
Fire a progress event named loadend.
When it is said to switch to the HEADERS_RECEIVED state run these steps:
Change the state to HEADERS_RECEIVED.
Fire an event named readystatechange.
When it is said to switch to the LOADING state run these steps:
Change the state to LOADING.
Fire an event named readystatechange.
When it is said to switch to the DONE state run these steps:
If the synchronous flag is set, update the response entity body.
Unset the synchronous flag.
Change the state to DONE.
Fire an event named readystatechange.
Fire a progress event named progress.
Fire a progress event named load.
Fire a progress event named loadend.
When it is said to make progress notifications, while the
download is progressing, queue a task to
fire a progress event named progress
about every 50ms or for every byte received, whichever is least
frequent.
When it is said to make upload progress notifications run these steps:
While the request entity body is being transmitted and the
upload complete flag is unset,
queue a task to
fire a progress event named progress on
the XMLHttpRequestUpload object about every 50ms or for
every byte transmitted, whichever is least frequent.
If the request entity body has been fully transmitted (irrespective of whether the server has started transmitting a response or the status code of such a response) and the upload complete flag is still unset, queue a task to run these substeps:
Set the upload complete flag.
Fire a progress event named progress
on the XMLHttpRequestUpload object.
Fire a progress event named load
on the XMLHttpRequestUpload object.
Fire a progress event named loadend
on the XMLHttpRequestUpload object.
abort() methodclient . abort()
The abort() method must run
these steps (unless otherwise noted):
Set the error flag.
The user agent should cancel any network activity for which the object is responsible.
If there are any
tasks from the
object's XMLHttpRequest task source in one of
the task queues,
then remove them.
If the state is UNSENT,
OPENED with the
send() flag being unset, or
DONE go to the next step.
Otherwise run these substeps:
Change the state to DONE.
Unset the send() flag.
Fire an event named readystatechange.
Fire a progress event named progress.
Fire a progress event named abort.
Fire a progress event named loadend.
If the upload complete flag is false run these substeps:
Set the upload complete flag to true.
Fire a progress event named progress
on the XMLHttpRequestUpload object.
Fire a progress event named abort
on the XMLHttpRequestUpload object.
Fire a progress event named loadend
on the XMLHttpRequestUpload object.
Change the state to UNSENT.
No readystatechange event is dispatched.
A response header is a HTTP response header transmitted before the response entity body. [HTTP]
This excludes trailer fields ("trailers").
status attributeclient . status
Returns the HTTP status code.
The
status
attribute must return the result of running these
steps:
If the error flag is set, return 0.
Return the HTTP status code.
statusText attributeclient . statusText
Returns the HTTP status text.
The
statusText
attribute must return the result of running these steps:
If the error flag is set, return the empty string.
Return the HTTP status text.
getResponseHeader() methodclient . getResponseHeader(header)
Returns the header field value from the response of which the
field name matches header, unless the field name is
Set-Cookie or Set-Cookie2.
The
getResponseHeader(header)
method must run these steps:
If the error flag is set, return null.
If header is a case-insensitive match for
Set-Cookie or Set-Cookie2, return null.
If header is a case-insensitive match for multiple response headers, return the values of these headers as a single concatenated string separated from each other by a U+002C COMMA U+0020 SPACE character pair.
If header is a case-insensitive match for a single response header, return the value of that header.
Return null.
The Cross-Origin Resource Sharing specification filters
response headers exposed by
getAllResponseHeaders()
for cross-origin requests.
[CORS]
For the following script:
var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(client.getResponseHeader("Content-Type"));
}
}
The print() function will get to process something
like:
text/plain; charset=UTF-8
getAllResponseHeaders() methodclient . getAllResponseHeaders()
Returns all headers from the response, with the exception of those
whose field name is Set-Cookie or
Set-Cookie2.
The
getAllResponseHeaders()
method must run these steps:
If the error flag is set, return the empty string.
Return all response headers, excluding headers that are a
case-insensitive match for Set-Cookie or
Set-Cookie2, as a single string, with each header line
separated by a U+000D CR U+000A LF pair, excluding the status line, and
with each header name and header value separated by a
U+003A COLON U+0020 SPACE pair.
The Cross-Origin Resource Sharing specification filters
response headers exposed by
getAllResponseHeaders()
for cross-origin requests.
[CORS]
For the following script:
var client = new XMLHttpRequest();
client.open("GET", "narwhals-too.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == 2) {
print(this.getAllResponseHeaders());
}
}
The print() function will get to process something
like:
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 response MIME type is the
MIME type the Content-Type header contains excluding any
parameters and
converted to ASCII lowercase, or null if
the response header can not be parsed 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 the header could
not be parsed 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 of the response received so far (LOADING) or the complete entity body of the response (DONE). If the response does not have an entity body, the response entity body is null.
The response entity body is updated as part
of the send() algorithm.
The
arraybuffer response entity body
is an ArrayBuffer representing
the response entity body. If the
arraybuffer response entity body has no value assigned to it
let it be the return value of the following algorithm:
If the response entity body is null, return an empty
ArrayBuffer object.
Return an ArrayBuffer
object representing the response entity body.
The
blob response entity body is a
Blob representing the response entity body. If
the blob response entity body has no value assigned to it let
it be the return value of the following algorithm:
If the response entity body is null, return an empty
Blob object.
Return a Blob object
representing the response entity body.
The document response entity body is either a document representing the response entity body or null. If the document response entity body has no value assigned to it let it be the return value of the following algorithm:
If the response entity body is null, return null.
If the JavaScript global environment is a worker environment, return null.
If final MIME type is not null,
text/html, text/xml,
application/xml, or does not end in
+xml, return null.
If responseType is
the empty string and final MIME type is
text/html, return null.
This is restricted to
responseType being
"document" in order to prevent breaking legacy
content.
If final MIME type is text/html, run these
substeps:
Let charset be the final charset.
If charset is null, prescan the first 1024 bytes of the response entity body and if that does not terminate unsuccessfully then let charset be the return value.
If charset is null, set charset to utf-8.
Decode byte stream response entity body using fallback encoding charset and then let document be a document that represents the result of that, parsed following the rules set forth in the HTML specification for an HTML parser with scripting disabled. [HTML]
Set document's encoding to charset.
Otherwise, let document be a document that represents the result of parsing the response entity body following the rules set forth in the XML specifications. If that fails (unsupported character encoding, namespace well-formedness error, etc.), 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.
Set document's content type to final MIME type.
Set document's URL to request URL.
Set document's origin to source origin.
Return document.
The JSON response entity body is an ECMAScript value representing the response entity body. The JSON response entity body is the return value of the following algorithm:
If the response entity body is null, return null.
Let JSON text be the result of running utf-8 decode on byte stream response entity body.
Return the result of invoking the parse function
of the JSON object defined in ECMAScript, with
JSON text as its only argument, or null if that function
throws an exception. [ECMASCRIPT]
The text response entity body is a string representing the response entity body. The text response entity body is the return value of the following algorithm:
If the response entity body is null, return the empty string.
Let charset be the final charset.
If responseType is
the empty string, charset is null, and
final MIME type is either null, text/xml,
application/xml or ends in +xml, use the
rules set forth in the XML specifications to determine the encoding. Let
charset be the determined encoding.
[XML] [XMLNS]
This is restricted to
responseType being
the empty string to keep the non-legacy
responseType value
"text" simple.
If charset is null, set charset to utf-8.
Return the result of running decode on byte stream response entity body using fallback encoding charset.
Authors are strongly encouraged to always encode their resources using utf-8.
overrideMimeType() methodclient . overrideMimeType(mime)
Sets the Content-Type header for the response to
mime.
Throws an "InvalidStateError"
exception if the state is
LOADING or
DONE.
Throws a "SyntaxError" exception if
mime is not a valid media type.
The
overrideMimeType(mime)
method must run these steps:
If the state is
LOADING or
DONE,
throw an
"InvalidStateError" exception.
If parsing mime analogously to the value of
the Content-Type header fails,
throw a
"SyntaxError" exception.
If mime is successfully parsed, set override MIME type to its MIME type, excluding any parameters, and converted to ASCII lowercase.
If a charset parameter is successfully parsed, set
override charset to its value.
responseType attributeclient . responseType [ = value ]
Returns the response type.
Can be set to change the response type. Values are:
the empty string (default),
"arraybuffer",
"blob",
"document",
"json", and
"text".
When set: setting to "document" is ignored if the
JavaScript global environment is a
worker environment
When set: throws an
"InvalidStateError" exception if the
state is LOADING or
DONE.
When set: throws an
"InvalidAccessError" exception if the
synchronous flag is set and the
JavaScript global environment is a
document environment.
The
responseType
attribute must return its value. Initially its value must be the empty
string.
Setting the
responseType
attribute must run these steps:
If the state is LOADING or
DONE,
throw an
"InvalidStateError" exception.
If the
JavaScript global environment is a
document environment and the
synchronous flag is set,
throw an
"InvalidAccessError" exception.
If the
JavaScript global environment is a
worker environment and the given
value is "document", terminate these steps.
Set the
responseType
attribute's value to the given value.
response attributeclient . response
Returns the response entity body.
The
response
attribute must return the result of running these
steps:
responseType
is the empty string or "text"If the state is not LOADING or DONE, return the empty string.
If the error flag is set, return the empty string.
Return the text response entity body.
If the state is not DONE, return null.
If the error flag is set, return null.
responseType is
"arraybuffer"Return the arraybuffer response entity body.
responseType is
"blob"Return the blob response entity body.
responseType is
"document"Return the document response entity body.
responseType is
"json"Return the JSON response entity body.
responseText attributeclient . responseText
Returns the text response entity body.
Throws an "InvalidStateError"
exception if
responseType is not
the empty string or "text".
The
responseText
attribute must return the result of running these
steps:
If responseType is not the
empty string or "text",
throw an
"InvalidStateError" exception.
If the state is not LOADING or DONE, return the empty string.
If the error flag is set, return the empty string.
Return the text response entity body.
responseXML attributeclient . responseXML
Returns the document response entity body.
Throws an "InvalidStateError"
exception if
responseType is not
the empty string or "document".
The
responseXML
attribute must return the result of running these steps:
If
responseType is not
the empty string or "document",
throw an
"InvalidStateError" exception.
If the state is not DONE, return null.
If the error flag is set, return null.
Return the document response entity body.
The
responseXML attribute
has XML in its name for historical reasons. It also returns HTML resources
as documents.
This section is non-normative.
The following events are dispatched on XMLHttpRequest
and/or XMLHttpRequestUpload objects:
| Event name | Interface | Dispatched when… |
|---|---|---|
readystatechange |
Event |
The readyState attribute changes
value, except when it changes to UNSENT.
|
loadstart |
ProgressEvent |
The fetch initiates. |
progress |
ProgressEvent |
Transmitting data. |
abort |
ProgressEvent |
When the fetch has been aborted. For instance, by invoking the
abort() method. |
error |
ProgressEvent |
The fetch failed. |
load |
ProgressEvent |
The fetch succeeded. |
timeout |
ProgressEvent |
The author specified timeout has passed before the fetch completed. |
loadend |
ProgressEvent |
The fetch completed (success or failure). |
FormDataThe FormData object represents an ordered collection of
entries. Each entry has a name, a value, a type, and optionally a filename
(if type is "file").
[Constructor(optional HTMLFormElement form)]
interface FormData {
void append(DOMString name, Blob value, optional DOMString filename);
void append(DOMString name, DOMString value);
};
fd = new FormData([form])
Returns a new FormData object, optionally initialized
with the data from form (if given).
fd . append(name, value [, filename])
Appends a new entry to the FormData object.
The
FormData(form)
constructor must run these steps:
Let fd be a new FormData object.
If form is given, set fd's entries to the result of constructing the form data set for form.
Return fd.
The
append(name, value, filename)
method must create a new entry with the following parameters set and append
it to the end of the collection the FormData object represents:
Set its name to name.
Set its value to value.
Set its type to "text" if value is a string and "file" if
it is a Blob.
If its type is "file" set its filename to "blob".
If its type is "file" and value is a
File whose
name attribute
is not the empty string, set entry's filename to the attribute's value.
If the filename parameter is not omitted set entry's filename to filename.
ProgressEvent[Constructor(DOMString type, optional ProgressEventInit eventInitDict)]
interface ProgressEvent : Event {
readonly attribute boolean lengthComputable;
readonly attribute unsigned long long loaded;
readonly attribute unsigned long long total;
};
dictionary ProgressEventInit : EventInit {
boolean lengthComputable;
unsigned long long loaded;
unsigned long long total;
}
Events using
the ProgressEvent interface indicate some kind of
progression.
The
lengthComputable
attribute must return the value it was initialized to. When an
event is created
the attribute must be initialized to false.
The
loaded and
total
attributes must return the value they were initialized to. When an
event is created
the attributes must be initialized to 0.
ProgressEvent interface for HTTPTo
fire a progress event named e
means to
fire an event named e
with an event
using the ProgressEvent interface that also meets these
conditions:
loaded
attribute to the number of HTTP
entity body bytes transferred.
Content-Length
header, initialize the
lengthComputable
attribute to true and initialize the
total attribute to the length.
ProgressEvent interface for other contextsThis is left as an exercise for the editor of the specification that
introduces such a context. The editor is encouraged to define it in a way
consistent with this and other specifications that utilize
events using the
ProgressEvent interface.
ProgressEvent interfaceThis section is non-normative.
The suggested type
attribute values for use with
events using the
ProgressEvent interface are summarized in the table below.
Specification editors are free to tune the details to their specific
scenarios, though are strongly encouraged to discuss their usage with the
WHATWG community to ensure input from people familiar with the subject.
type attribute value
| Description | Times | When |
|---|---|---|---|
loadstart
| Progress has begun. | Once. | First. |
progress
| In progress. | Zero or more. | After loadstart has been
dispatched.
|
error
| Progression failed. | Zero or once. | After the last progress has
been
dispatched,
or after loadstart has been
dispatched
if progress has not been
dispatched.
|
abort
| Progression is terminated. | Zero or once. | |
load
| Progression is successful. | Zero or once. | |
loadend
| Progress has stopped. | Once. | After one of error,
abort, or load has been
dispatched.
|
The error, abort, and
load event types are mutually exclusive.
Throughout the web platform the error,
abort, and load event types have
their bubbles and
cancelable
attributes initialized to false, so it is suggested that for consistency all
events using the
ProgressEvent interface do the same.
For cross-origin requests some kind of opt-in, e.g.
Cross-Origin Resource Sharing, has to be used before
events using the
ProgressEvent interface are
dispatched
as information (e.g. size) would be revealed that cannot be obtained
otherwise. [CORS]
In this example XMLHttpRequest, combined with concepts
defined in the sections before, and the HTML
progress element are used together to
display the process of
fetching a resource.
<!DOCTYPE html>
<title>Waiting for Magical Unicorns</title>
<progress id=p></progress>
<script>
var progressBar = document.getElementById("p"),
client = new XMLHttpRequest()
client.open("GET", "magical-unicorns")
client.onprogress = function(pe) {
if(pe.lengthComputable) {
progressBar.max = pe.total
progressBar.value = pe.loaded
}
}
client.onloadend = function(pe) {
progressBar.value = pe.loaded
}
client.send()
</script>
Fully working code would of course be more elaborate and deal with more scenarios, such as network errors or the end user terminating the request.
data: URLs and HTTPTo ensure
data: URLs
can function in APIs designed around HTTP, such as
XMLHttpRequest, this section details how they work.
Specifications defining similar URL schemes ought to take inspiration from
this section.
When a
data: URL is
fetched using the HTTP method
GET, determine the response as follows:
Ignore any request headers.
Set the HTTP status code to 200.
Set the HTTP status text to "OK".
Include a single response header whose header field name is
"content-type" and whose value is the
MIME type (including any parameters) given in the
data: URL,
or the default otherwise.
Set the response entity body to the data the
URL encodes, base64 decoded if the
";base64" flag is present.
Otherwise, including when the
data: URL cannot be
parsed, this is a network error.
The editor would like to thank Addison Phillips, Adrian Bateman, Ahmed Kamel, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Andrea Marchesini, Asbjørn Ulsberg, Boris Zbarsky, Björn Höhrmann, Cameron McCormack, Chris Marrin, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Andersson, David Flanagan, David Håsäther, David Levin, Dean Jackson, Denis Sureau, Dominik Röttsches, Doug Schepers, Douglas Livingstone, Elliott Sprehn, Elliotte Harold, Eric Lawrence, Eric Uhrhane, Erik Dahlström, Feras Moussa, Geoffrey Sneddon, Gideon Cohn, Glenn Adams, Gorm Haug Eriksen, Håkon Wium Lie, Hallvord R. M. Steen, Henri Sivonen, Huub Schaeks, Ian Davis, Ian Hickson, Ivan Herman, Jarred Nicholls, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, 呂康豪 (Kang-Hao Lu), Karl Dubost, Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mark S. Miller, Martin Hassman, Mohamed Zergaoui, Ms2ger, Odin Hørthe Omdal, Olli Pettay, Pawel Glowacki, Peter Michaux, Philip Taylor, Robin Berjon, Rune Halvorsen, Ruud Steltenpool, Sergiu Dumitriu, Sigbjørn Finne, Simon Pieters, Stewart Brodie, Sunava Dutta, Thomas Roessler, Tom Magliery, Travis Leithead, Yehuda Katz, and Zhenbin Xu for their contributions to this specification.
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 drafting an initial version of this specification in their Web Applications 1.0 document (now renamed to HTML). [HTML]
Special thanks to the SVG WG for drafting the original
ProgressEvent interface as part of the
SVG Micro DOM.
Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)