XMLHttpRequest

This object is available to unprivileged JavaScript. It implements the following interfaces:

Properties

readonly nsIChannel channel

The request uses a channel in order to perform the request. This attribute represents the channel used for the request. NULL if the channel has not yet been created.

In a multipart request case, this is the initial channel, not the different parts in the multipart request.

Mozilla only. Requires elevated privileges to access.

boolean multipart

Set to true if the response is expected to be a stream of possibly multiple (XML) documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will be triggerd. All requests must be asynchronous.

This enables server push. For each XML document that's written to this request, a new XML DOM document is created and the onload handler is called inbetween documents. Note that when this is set, the onload handler and other event handlers are not reset after the first XML document is loaded, and the onload handler will be called as each part of the response is received.

EventListener onerror

Meant to be a script-only mechanism for setting an error event listener. The attribute is expected to be JavaScript function object. When the error event occurs, the function is invoked. This attribute should not be used from native code!!

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

Mozilla only.

EventListener onload

Meant to be a script-only mechanism for setting a load event listener. The attribute is expected to be JavaScript function object. When the load event occurs, the function is invoked. This attribute should not be used from native code!!

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

Mozilla only.

EventListener onprogress

Meant to be a script-only mechanism for setting a progress event listener. The attribute is expected to be JavaScript function object. When the error event occurs, the function is invoked. This attribute should not be used from native code!! This event listener may be called multiple times during the open request.

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

Mozilla only.

nsIOnReadyStateChangeHandler onreadystatechange

Meant to be a script-only mechanism for setting a callback function. The attribute is expected to be JavaScript function object. When the readyState changes, the callback function will be called. This attribute should not be used from native code!!

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

readonly PRInt32 readyState

The state of the request.

Possible values: 0 UNINITIALIZED open() has not been called yet. 1 LOADING send() has not been called yet. 2 LOADED send() has been called, headers and status are available. 3 INTERACTIVE Downloading, responseText holds the partial data. 4 COMPLETED Finished with all operations.

readonly AString responseText

The response to the request as text. NULL if the request is unsuccessful or has not yet been sent.

readonly Document responseXML

The response to the request is parsed as if it were a text/xml stream. This attributes represents the response as a DOM Document object. NULL if the request is unsuccessful or has not yet been sent.

readonly int status

The status of the response to the request for HTTP requests.

readonly AUTF8String statusText

The string representing the status of the response for HTTP requests.


Methods

void abort ( ) void addEventListener ( String type , EventListener listener , boolean useCapture ) boolean dispatchEvent ( Event evt ) char* getAllResponseHeaders ( ) ACString getResponseHeader ( AUTF8String header ) void open ( AUTF8String method , AUTF8String url ) [noscript] void openRequest ( AUTF8String method , AUTF8String url , boolean async , AString user , AString password ) void overrideMimeType ( AUTF8String mimetype ) void removeEventListener ( String type , EventListener listener , boolean useCapture ) void send ( nsIVariant body ) void setRequestHeader ( AUTF8String header , AUTF8String value )

void abort ( )

If the request has been sent already, this method will abort the request.


void addEventListener ( String type , EventListener listener , boolean useCapture )

This method allows the registration of event listeners on the event target. If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.

If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded. They do not cause the EventListener to be called twice and since they are discarded they do not need to be removed with the removeEventListener method.

Arguments:
type: The event type for which the user is registering
listener: The listener parameter takes an interface implemented by the user which contains the methods to be called when the event occurs.
useCapture: If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered EventListener before being dispatched to any EventTargets beneath them in the tree. Events which are bubbling upward through the tree will not trigger an EventListener designated to use capture.

boolean dispatchEvent ( Event evt )

This method allows the dispatch of events into the implementations event model. Events dispatched in this manner will have the same capturing and bubbling behavior as events dispatched directly by the implementation. The target of the event is the EventTarget on which dispatchEvent is called.

Arguments:
evt: Specifies the event type, behavior, and contextual information to be used in processing the event.
Returns:
Indicates whether any of the listeners which handled the event called preventDefault. If preventDefault was called the value is false, else the value is true.

char* getAllResponseHeaders ( )

Returns all of the response headers as a string for HTTP requests.

Note that this will return all the headers from the *current* part of a multipart request, not from the original channel.


ACString getResponseHeader ( AUTF8String header )

Returns the text of the header with the specified name for HTTP requests.

Arguments:
header: The name of the header to retrieve

void open ( AUTF8String method , AUTF8String url )

Meant to be a script-only method for initializing a request. The parameters are similar to the ones detailed in the description of openRequest, but the last 3 are optional.

Will abort currently active loads.

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

Arguments:
method: The HTTP method - either "POST" or "GET". Ignored if the URL is not a HTTP URL.
url: The URL to which to send the request.

void openRequest ( AUTF8String method , AUTF8String url , boolean async , AString user , AString password )

Native (non-script) method to initialize a request. Note that the request is not sent until the send method is invoked.

Will abort currently active loads.

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

Arguments:
method: The HTTP method, for example "POST" or "GET". Ignored if the URL is not a HTTP(S) URL.
url: The URL to which to send the request.
async: Whether the request is synchronous or asynchronous i.e. whether send returns only after the response is received or if it returns immediately after sending the request. In the latter case, notification of completion is sent through the event listeners. This argument must be true if the multipart attribute has been set to true, or an exception will be thrown.
user: A username for authentication if necessary.
password: A password for authentication if necessary.

void overrideMimeType ( AUTF8String mimetype )

Override the mime type returned by the server (if any). This may be used, for example, to force a stream to be treated and parsed as text/xml, even if the server does not report it as such. This must be done before the send method is invoked.

Arguments:
mimetype: The type used to override that returned by the server (if any).

void removeEventListener ( String type , EventListener listener , boolean useCapture )

This method allows the removal of event listeners from the event target. If an EventListener is removed from an EventTarget while it is processing an event, it will not be triggered by the current actions. EventListeners can never be invoked after being removed. Calling removeEventListener with arguments which do not identify any currently registered EventListener on the EventTarget has no effect.

Arguments:
type: Specifies the event type of the EventListener being removed.
listener: The EventListener parameter indicates the EventListener to be removed.
useCapture: Specifies whether the EventListener being removed was registered as a capturing listener or not. If a listener was registered twice, one with capture and one without, each must be removed separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.

void send ( nsIVariant body )

Sends the request. If the request is asynchronous, returns immediately after sending the request. If it is synchronous returns only after the response has been received.

After the initial response, all event listeners will be cleared. Call open() before setting new event listeners.

Arguments:
body: Either an instance of nsIDOMDocument, nsIInputStream or a string (nsISupportsString in the native calling case). This is used to populate the body of the HTTP request if the HTTP request method is "POST". If the parameter is a nsIDOMDocument, it is serialized. If the parameter is a nsIInputStream, then it must be compatible with nsIUploadChannel.setUploadStream, and a Content-Length header will be added to the HTTP request with a value given by nsIInputStream.available. Any headers included at the top of the stream will be treated as part of the message body. The MIME type of the stream should be specified by setting the Content- Type header via the setRequestHeader method before calling send.

void setRequestHeader ( AUTF8String header , AUTF8String value )

Sets a HTTP request header for HTTP requests. You must call open before setting the request headers.

Arguments:
header: The name of the header to set in the request.
value: The body of the header.

Reference documentation is generated from Mozilla's source.

Add a note User Contributed Notes
November 10, 2005, 2:06 pm abdullah dot a at gmail dot com
If you make a POST request to a URL that redirects (for example a subdomain that redirects to a directory in the domain i.e sub.domain.com -> domain.com/sub/), the POST data supplied to .send will not presist throughout the redirection. I learned this the hard way.
November 3, 2005, 5:54 am wooyay at web dot de
it would be nice if there was a way to see if a multipart connection is still running. It seems that when the connection is broken by the server, the readyState changes to 2.
August 17, 2005, 8:13 am birdman at acceleration dot net
readyState:
If you are trying to implement this in a cross-browser manner, note that the readyState property is different in Mozilla's implementation vs Microsoft's implementation.
June 13, 2005, 1:24 pm pike-mozilla at kw dot nl
To make the body of an HTTP POST request look the same as a form POST, you need to set the request header ‘Content-Type: application/x-www-form-urlencoded’, like in

xmlhttp.open(bla,bla,bla)
xmlhttp.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);

You also need to encode the data in the body in a similar fashion to GET parameters, using the & character to separate each variable and = for assignments (but you don’t need the initial ? character)
March 24, 2005, 6:01 am richard at redferret dot co dot za
The XMLHTTPRequest technique for retrieving data behind the user's page is gaining popularity and there was an article on it at <a href="http://www.sitepoint.com">SitePoint</a> referring to it as AJAX (Advanced Javascripting and XML). The possibilities are enourmous for developing rich web applications and some work has already been done to develop a simple architecture for accessing functionality from a webpage through this technique.

One example of a page making calls to functionality on a server can be found at <a href="http://www.redferret.co.za/aframe">http://redferreet.co.za/aframe</a> where users can use a dynamically generated form to query any of a number of services from the webserver.
March 10, 2005, 12:41 pm asqueella at gmail dot com
A few examples are available at http://kb.mozillazine.org/XMLHttpRequest
March 4, 2005, 8:25 pm mg at ideasfreelance dot com
http://manoloweb.blogspot.com/2005/03/instant-editor.html
A very useful live field editor using xmlHttpRequest I wrote, it is only an idea, but I believe that many users will find an ocean of possibilities.
November 10, 2004, 6:24 am richard at trinet dot co dot uk
getResponseHeader will throw an exception if the header is not available:
0x80040111 NS_ERROR_NOT_AVAILABLE
October 15, 2004, 12:28 pm patrickc-nospam at plumtree dot com
It should be noted that the open() method will throw a "permission denied" exception in unprivileged mode if the requested URL is not in the same domain as the URL of the host.
August 7, 2004, 6:26 am development at acriba dot at
I just found out, that you can use serverside sessions with XMLHttpRequest. Cookies are set automatically, you don't have to do any extra work. Isn't that wonderful?
May 25, 2004, 12:31 am hfuecks at phppatterns dot com
Note the open() method has the same signature as the openRequest() method, not that described above, i.e.


void open ( AUTF8String method , AUTF8String url , boolean async , AString user , AString password )
April 18, 2004, 10:41 am dvdplm at yahoo dot com
Watch out for multiple asynchronous requests triggered for example in a loop ("for every child element, do this POST:..."). In my case it was enough making a "delete(req)" at the end of the loop and thus making sure to avoid confusion with several ongoing requests having the same variable name.

Synchronous XMLHttpRequests inside loops have problems: up to 10 seconds for each request to even leave the browser...

(Win2000, FF0.8, Apache)
April 18, 2004, 10:40 am hfuecks at phppatterns dot com
Connecting XUL Applications with PHP - tutorial demonstrating use of XMLHttpRequest request / response to PHP script.

Copyright © 1999 - 2005 XULPlanet.com