XMLHttpRequest
XMLHttpRequest (XHR) is an API that can be used by JavaScript, and other web browser scripting languages to transfer XML and other text data to and from a web server using HTTP, by establishing an independent and asynchronous communication 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 such as HTML, JSON or 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 web applications that make use of XMLHttpRequest include Google's Gmail service, Meebo, Google Maps, Windows Live's Virtual Earth, the MapQuest dynamic map interface, Facebook and many others.
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. |
Properties
| Property | Description |
|---|---|
| onreadystatechange | Specifies a reference to an event handler for an event that fires at every state change. |
| readyState | Returns the state of the object as follows:
|
| 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. |
| responseBody | Returns the response as a binary encoded string which can be decoded and viewed using the following vbscript function:
Dim q, S
For q = 1 to LenB(objHTTP.ResponseBody)
S = S & Chr(AscB(MidB(objHTTP.ResponseBody,q,1)))
Next
wscript.echo S
|
| status | Returns the HTTP status code as a number (e.g. 404 for "Not Found" and 200 for "OK"). Some network-related status codes (e.g. 408 for "Request Timeout") cause errors to be thrown in Firefox if the status fields are accessed [2]. If server does not respond (properly), IE returns a WinInet Error Code (e.g 12029 for "cannot connect"). |
| 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, as a server side API call, so not still a standards-based web client feature, but de facto, support for it has been implemented by many major web browsers. The Microsoft implementation is called XMLHTTP. It has been available since Internet Explorer 5.0[3] 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.[4] 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:
- Invisible inline frames (or NN4 equivalent ilayer's)
- Remote Scripting
- Netscape's LiveConnect
- Microsoft's ActiveX
- Microsoft's XML Data Islands
- Adobe Flash Player
- Java Applets
- Image wrappers (probably the oldest method available, possible since NN3 implementations)
- DOM metascripting
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.[5]
Here is a cross-browser general purpose example of an AJAX/XMLHttpRequest JavaScript function
<source lang="JavaScript"> function ajax(url, vars, callbackFunction){
var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
request.open("POST", url, true); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200) {
if (request.responseText){
callbackFunction(request.responseText); } } } request.send(vars); } </source>
Known problems
Caching
Most of the implementations also realise HTTP caching. Internet Explorer and Firefox do, but there is a difference in how and when the cached content is revalidated.
Firefox revalidates the cached response every time the page is refreshed, issuing an "If-Modified-Since" header with value set to the value of the "Last-Modified" header of the cached response.
Internet Explorer does so only if the cached response is expired (i.e., after the date of received "Expires" header).
This raises some issues, and it is widely believed that a bug exists in Internet Explorer, and the cached response is never refreshed.
It is possible to unify the caching behaviour on the client. The following script illustrates an example approach: <source lang="JavaScript">
var request = (typeof(XMLHttpRequest) != "undefined") ? new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
request.open("GET", uri, false);
request.send(null);
if(!request.getResponseHeader("Date"))
{
var cached = request;
request = (typeof(XMLHttpRequest) != "undefined") ? new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
var ifModifiedSince = cached.getResponseHeader("Last-Modified");
ifModifiedSince = (ifModifiedSince) ? ifModifiedSince : new Date(0); // January 1, 1970
request.open("GET", uri, false);
request.setRequestHeader("If-Modified-Since", ifModifiedSince);
request.send("");
if(request.status == 304)
{
request = cached;
}
}
</source> In Internet Explorer, if the response is returned from the cache without revalidation, the "Date" header is an empty string. The workaround is achieved by checking the "Date" response header and issuing another request if needed. In case a second request is needed, the actual HTTP request is not made twice, as the first call would not produce an actual HTTP request.
The reference to the cached request is preserved, because if the response code/status of the second call is "304 Not Modified", the response body becomes an empty string ("") and then it is needed to go back to the cached object. A way to save memory and expenses of second object creation is to preserve just the needed response data and reuse the XMLHttpRequest object.
The above script relies on the assumption that the "Date" header is always issued by the server, which should be true for most server configurations. Also, it illustrates a synchronous communication between the server and the client. In case of asynchronous communication, the check should be made during the callback.
This problem is often overcome by employing techniques preventing the caching at all. Using these techniques indiscriminately can result in poor performance and waste of network bandwidth.
Workaround
Internet Explorer will also cache dynamic pages, this is because the URI of the page may not change but the content will (For example a news feed). A work around for this situation can be achieved by adding a unique time stamp or random number, or possibly both, typically using the Date object and/or Math.random().
For simple document request the query string delimiter '?' can be used, or for existing queries a final sub-query can be added after a final '&' – to append the unique query term to the existing query. The downside is that each such request will fill up the cache with useless (never reused) content that could otherwise be used for other cached content (more useful data will be purged from cache to make room for these one-time responses).
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.
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. Konqueror, 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.[3]
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.
References
- ^ - W3C Working Draft 27 February 2007 section 2.2
- ^ The XMLHttpRequest Object, W3C Working Draft
- ^ a b Dutta, Sunava (2006-01-23). Native XMLHTTPRequest object. IEBlog. Microsoft. Retrieved on 2006-11-30.
- ^ Bugzilla@Mozilla – Bug 238559 18 October 2007
- ^ Document Object Model (DOM) Level 3 Load and Save Specification, V 1.0, W3C Recommendation 07 April 2004
See also
External links
Documentation/Browser implementations
- The XMLHttpRequest Object — W3C Working Draft
- Apple Safari 1.2
- Microsoft IXMLHTTPRequest
- Mozilla XML Extras
Tutorials
- Very Dynamic Web Interfaces
- Ajax tutorial for creating client-side dynamic web pages
- Call SOAP Web services with Ajax, Part 1: Build the Web services client
Security
- "Attacking AJAX Applications", a presentation given at the Black Hat security conference. Discusses several issues involving XHR and the future of cross-domain AJAX.
This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)






