Opentopia Directory Encyclopedia Tools

XMLHttpRequest

Encyclopedia : X : XM : XML : XMLHttpRequest


XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.

XMLHttpRequest is an important part of the Ajax web development technique, and it is used by many websites to implement responsive and dynamic web applications. Examples of XMLHttpRequest applications include Google's Gmail service, Google Suggest dynamic look-up interface, Meebo, MSN's Virtual Earth and the MapQuest dynamic map interface.

Methods

Method Description
abort() Cancels the current request.
getAllResponseHeaders() Returns the complete set of HTTP headers as a string.
getResponseHeader( headerName ) Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of "GET", "POST", or "PUT" ("GET" is used when requesting data and use "POST" when sending data, especially if the length of the data is greater than 512 bytes).

The URL parameter may be either a relative or complete URL.

The "async" parameter specifies whether the request should be handled asynchronously or not – "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.

send( content ) Sends the request.
setRequestHeader( label, value ) Adds a label/value pair to the HTTP header to be sent.

Properties

Property Description
onreadystatechange An event handler for an event that fires at every state change.
readyState Returns the state of the object as follows: 0 = uninitialized, 1 = open, 2 = sent, 3 = receiving and 4 = loaded.
responseText Returns the response as a string.
responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
status Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
statusText Returns the status as a string (e.g. "Not Found" or "OK").

History and support

The XMLHttpRequest concept was originally developed by Microsoft as part of Outlook Web Access 2000. The Microsoft implementation is called XMLHTTP and, as an ActiveX object, it differs from the published standard in a few small ways. It has been available since Internet Explorer 5.0. and is accessible via JScript, VBScript and other scripting languages supported by IE browsers.

The Mozilla project incorporated the first compatible native implementation of XMLHttpRequest in Mozilla 1.0 in 2002. This implementation was later followed by Apple since Safari 1.2, Konqueror, Opera Software since Opera 8.0 and iCab since 3.0b352.

The World Wide Web Consortium published a Working Draft specification for the XMLHttpRequest object's API on 5 April 2006[link]. While this is still a work in progress, its goal is "to document a minimum set of interoperable features based on existing implementations, allowing Web developers to use these features without platform-specific code". The draft specification is based upon existing popular implementations, to help improve and ensure interoperability of code across web platforms.

Web pages that use XMLHttpRequest or XMLHTTP can mitigate the current minor differences in the implementations either by encapsulating the XMLHttpRequest object in a JavaScript wrapper, or by using an existing framework that does so. In either case, the wrapper should detect the abilities of current implementation and work within its requirements.

Traditionally, there have been other methods to achieve a similar effect of server dynamic applications using scripting languages and/or plugin technology:

Known problems

Microsoft Internet Explorer cache issues

Internet Explorer implements caching for GET requests. Authors who are not familiar with HTTP caching expect GET requests not to be cached, or for the cache to be avoided as with the refresh button. In some situations, failing to circumvent caching is a bug. One solution to this is to use the POST request method, which is never cached; however, it is intended for non-idempotent operations. A solution using the GET request method is to include a unique (previously unused) query string with each call, as shown in the example below.

req.open("GET", "xmlprovider.php?hash=" + Math.random());
Setting the "Expires" header to reference a date in the past will also avoid caching of the response. Here is an example in PHP.

header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );  // disable IE caching
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header( "Cache-Control: no-cache, must-revalidate" );
header( "Pragma: no-cache" );
Caching may also be disabled, as in this Java Servlet example.

response.setHeader( "Pragma", "no-cache" );
response.addHeader( "Cache-Control", "must-revalidate" );
response.addHeader( "Cache-Control", "no-cache" );
response.addHeader( "Cache-Control", "no-store" );
response.setDateHeader("Expires", 0);
Alternatively, it is possible to force the XMLHttpRequest object to retrieve the content anyway, as shown in this example.

req.open( "GET", "xmlprovider.php" );
req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
req.send( null );
It is important to note that these techniques should be used only if the caching is inappropriate. Generally it is better to obtain the performance benefits of caching, perhaps combined with explicitly detailing modification dates or other relevant headers on the server so as to get as much caching as possible without it causing poor results.

Many programmers use the techniques above indiscriminately, which can result in a significant reduction in performance.

Problems with accented and non-ASCII characters

If the server answer does not encapsulate the result in an XML format, the 'responseText' may not work correctly when using non-ASCII characters, for example accented characters like é. Although Firefox copes with such data, Internet Explorer will only handle it properly for the first request (although there may be display problems). If the request is repeated and Internet Explorer uses a cached result, then it will generate a JavaScript error.

XML formatted results and the use of a slightly more complex 'responseXML' method will work with any UTF-8 characters.

Reusing XMLHttpRequest Object in IE

In IE, if the open method is called after setting the onreadystatechange callback, there will be a problem when trying to reuse the XHR object. To be able to reuse the XHR object properly, use the open method first and set onreadystatechange later. This happens because IE resets the object implicitly in the open method if the status is 'completed'. For more explanation of reuse: [Reusing XMLHttpRequest Object in IE.]

Cross Browser Support

Microsoft developers were the first to include XMLHttp object in their MSXML ActiveX control. Developers at the open source Mozilla project saw this invention and ported their own XMLHttp, but not as an ActiveX control but as a native browser object called XMLHttpRequest. Opera and Safari have since implemented similar functionality but more along the lines of Mozilla's XMLHttpRequest. Some Ajax developer and run-time frameworks only support one implementation of XMLHttp while others support both. Developers building Ajax functionality from scratch can provide if/else logic within their client-side JavaScript to use the appropriate XMLHttp object as well.

See also

External links

Documentation/Browser implementations

Tutorials

 


From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.

Search Titles
0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ?

E-mail this article to:

Personal Message: