XMLHttpRequest

From Wikipedia, the free encyclopedia

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, Google Earth, MSN's Virtual Earth and the MapQuest dynamic map interface.

Contents

[edit] 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", "HEAD", "PUT", "DELETE", or a variety of other HTTP methods listed in the W3C specification.[1]

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.

[edit] 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
  • 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 HTTP status code 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").

[edit] 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[1]. 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:

In addition, the World Wide Web Consortium has several Recommendations that also allow for dynamic communication between a server and user agent, though few of them are well supported. These include:

  • The object element defined in HTML 4 for embedding arbitrary content types into documents, (replaces inline frames under XHTML 1.1)
  • The Document Object Model (DOM) Level 3 Load and Save Specification [2]

[edit] Known problems

[edit] 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.

Setting the "Expires" header to reference a date in the past will 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 );

Another method is to add a random string on the end of the url in the query:

req.open( "GET", "xmlprovider.php?sid=" + Math.random());

This will ensure that the browser always gets a fresh copy.

It is important to note that these techniques should be used only if the caching is inappropriate. If such methods are used indiscriminately, poor performance with the application may result. Another better way around that may be sending an expired date/time header (or other relevant headers) to the client to gain benefits from caching while letting the client know that new data may be available, as generally it is better to obtain the performance benefits from caching to reduce processing time and bandwidth consumption.

[edit] 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.

For accented characters, if UTF-8 doesn't display them correctly, you may use ISO-8859-1 instead.

For example :

<?xml version="1.0" encoding="ISO-8859-1"?>
<ajax-response>
éêèâàïîç - will be displayed correctly
</ajax-response>

[edit] 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.. The downside to calling the open method after setting the callback is a loss of cross-browser support for readystates. See the quirksmode article.

[edit] Cross-browser support

Microsoft developers were the first to include the XMLHttp object in their MSXML ActiveX control. Developers at the open source Mozilla project saw this invention and ported their own XMLHttp, 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. Internet Explorer 7 added native support for the XMLHttpRequest object, but retains backward-compatibility with the ActiveX implementation.[2]

[edit] Frameworks

Because of the complexity of handling cross-browser distinctions between XMLHttpRequest implementations, a number of frameworks have emerged to abstract these differences into a set of reusable programming constructs. Examples of frameworks include Dojo Toolkit and the Atlas Framework.

[edit] References

  1. ^ - W3C Working Draft 27 September 2006 section 2.2
  2. ^ Dutta, Sunava (2006-01-23). Native XMLHTTPRequest object. IEBlog. Microsoft. Retrieved on 2006-11-30.

[edit] See also

[edit] External links

[edit] Documentation/Browser implementations

[edit] Tutorials

[edit] Security