JavaScript/XMLHttpRequest

From Wikibooks, open books for an open world
< JavaScript
Jump to: navigation, search

This is a guide and reference to the XMLHttpRequest object, a key component to know in Ajax programming.

Example[edit]

Here is a brief example of a web page that uses XMLHttpRequest. We'll get into the details and ways to work-around various things that can go wrong later.

<html><!-- example.html : public domain -->
<script language="JavaScript" type="text/JavaScript" >
function alertContents(httpRequest){
    if (httpRequest.readyState == 4){
        // everything is good, the response is received
        if ((httpRequest.status == 200) || (httpRequest.status == 0)){
            // FIXME: perhaps a better example is to *replace* some text in the page.
            var htmlDoc=document.createElement('div'); // Create a new, empty DIV node.
            htmlDoc.innerHTML = httpRequest.responseText; // Place the returned HTML page inside the new node.
            alert( "The response was: " + httpRequest.status + httpRequest.responseText);
        }else{
            alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
        }
    }
}
 
function send_with_ajax( the_url ){
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() { alertContents(httpRequest); };  
    httpRequest.open("GET", the_url, true);
    httpRequest.send(null);
}
</script>
 
<p onClick="send_with_ajax('example.html');">
Click me!
</p>
</html>

Object reference[edit]

Methods[edit]

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.
  • 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. content can be a string or reference to a document.
setRequestHeader(label, value)
Adds a label/value pair to the HTTP header to be sent.

Properties[edit]

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:
  • 0 = uninitialized – open() has not yet been called.
  • 1 = open – send() has not yet been called.
  • 2 = sent – send() has been called, headers and status are available.
  • 3 = receiving – Downloading, responseText holds partial data
  • 4 = loaded – Finished.
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. This property is not part of the native XMLHttpRequest wrapper. For this property to be available, the XHR object must be created with an ActiveX component. A JScript example:
if(typeof ActiveXObject != "undefined") {
  xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
  xmlhttp.open("GET", "#", false);
  xmlhttp.send(null);
  alert(xmlhttp.responseBody);
} else {
  alert("This browser does not support Microsoft ActiveXObjects.")
}
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. If the 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").

Bugs and inconsistencies[edit]

Dealing with bugs and inconsistencies in XMLHttpRequest implementations:

Caching[edit]

Most of the implementations also realize HTTP caching. Internet Explorer and Firefox do, but there is a difference in how and when the cached data 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, since a bug exists in Internet Explorer, where the cached response is never refreshed.

It is possible to unify the caching behavior on the client. The following script illustrates an example approach:

var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
if(!request.getResponseHeader("Date")) {
  var cached = request;
  request = new XMLHttpRequest();
  var ifModifiedSince =
    cached.getResponseHeader("Last-Modified") ||
    new Date(0); // January 1, 1970
  request.open("GET", url, false);
  request.setRequestHeader("If-Modified-Since", ifModifiedSince);
  request.send("");
  if(request.status == 304) {
    request = cached;
  }
}

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.

If script executes operation that has side effects (e.g. adding a comment, marking message as read) which requires that request always reaches the end server, it should use POST method instead.

Workaround[edit]

Internet Explorer will also cache dynamic pages and this is a problem because the URL of the page may not change but the content will (for example a news feed). A workaround 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).

A better workaround can be achieved by adding meta tags to dynamic pages in order to make them no-cachable:

<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

Reusing XMLHttpRequest Object in IE[edit]

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.

Links[edit]

Further reading[edit]