XMLHttpRequest object usage

Summary of the specification by W3C, and usage

This server side object is used by JavaScript to exchange data with the server, in plain text, XML or JSON format. The XML format is automatically parsed by the object at loading and accessible by DOM's methods. JSON files are parsed by the eval() JavaScript command. In Internet Explorer, it is an Active X object.

Summary

Brief history

XMLHttpRequest, was first implemented by Internet Explorer since the 4.0 version.
The same concept was named XMLHTTP some times, before the Ajax name becomes commonly used.
The use of XMLHttpRequest in 2005 by Google, in Gmail and GoogleMaps has contributed to the success of this technology.

Description


This is a class that is recognized by all current browsers, and by the JavaScript client side programming language.
For each request to the server, a new instance is created by a call to the constructor.
The open method starts the connection, in read or write mode, to receive data from the server or send it. It will be processed by the server with a server side language as PHP, Java, etc...
The connection takes several successive states that are assigned to the readyState attribute of the object.
When the final state is reached, the data may be found in another attribute. It may be a plain text or an XML document. The JSON format is loaded as plain text and parsed by JavaScript.
More details on the use of the class in the Ajax tutorial.

Attributes

The purpose of attributes of the class is to be assigned the status of the connection, and to hold data.

unsigned short readyState
The code successively changes value until the server is ready, from 0 to 4 .
  • 0 Not initialized
  • 1 Open
  • 2 Sent
  • 3 Received
  • 4 Loaded
unsigned short status
200 is ok
404 if the page is not found.
DOMString statusText
Holds the label of the status, corresponding to the status code.
DOMString responseText
Holds loaded data as a string of characters. It is completely filled when the status is 4.
DOMDocument responseXml
Holds an XML loaded file, and DOM's methods allow to extract data. It is filled only when the code is 4 and null otherwise.
EventListener onreadystatechange
Invoked when readyState is assigned.

Methods

Apart the constructor, the class has two main methods, open to create a session and designate the distant file, and send to move data to the server.

abort()
Resets the object and stops any activity created by the object.
getAllResponseHeaders()
Return all headers into a string, separated by CR and LF codes.
getResponseHeader(DOMString)
Return the header of data received, after the last request. Several headers should be separated by a comma plus a space.
open(mode, url, boolean [, login, password])
mode: type of request, GET, POST, HEAD or other http methods.
url: the location of the file, with a path.
boolean: true (asynchronous) / false (synchronous).
optionally, a login and a password as additional arguments.
send("string")
null or empty with a GET command, a string otherwise.
Raises a DOMException (INVALID_STATE_ERR) if the readyState code is not 1.
setRequestHeader(DOMString, DomString)
Arguments are the name of the header and the value. Several values may be successively sent.
Raises a DOMException (INVALID_STATE_ERR) if the readyState code is not 1.

How to use XMLHttpRequest

The class is a part of ECMAScript (JavaScript) and used as any other class of the language, but there are several constructors according to the browser. Here is a complete code to open an Ajax session, by creating a new XMLHttpRequest object and loading some data.
The code may be tested with several demos on the Ajax tutorial and in the Ajax sub-domain.

<html>
<head>
<script language="JavaScript">

 function submitForm()
 {
    var xhr=null;

   try
   {
     xhr = new XMLHttpRequest(); 
   } catch(e)
   { 
     try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } 
     catch (e2)
    { 
       try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } 
       catch (e) {}
    }
  }

  xhr.onreadystatechange = function()
   { 
     document.ajax.dyn.value="Wait server...";                
     if(xhr.readyState == 4)
     {
        if(xhr.status == 200)
        { 
             document.ajax.dyn.value="Received:" + xhr.responseText; 
        } 
       else 
        { 
              document.ajax.dyn.value="Error: returned status code " + 
                   xhr.status + " " + xhr.statusText; 
       } 
    } 
 }; 

 xhr.open("GET", "data.xml", true);                
 xhr.send(null); 
}

</script>
</head>
               
<body>
   <FORM method="POST" name="ajax" action="">                
    <INPUT type="submit" value="Submit" ONCLICK="submitForm()">
    <INPUT type="text" name="dyn" value=""> 
   </FORM>
</body>
</html> 

Caching problem

Memory cache does not work properly with the object. Often, the file loaded by the GET method is not the last version, but an older version taken from the memory buffer. If the file is not too big, this can be overcomed easily by adding a parameter to the command. Replace:

xhr.open("GET", "data.xml", true); 

by:

xhr.open("GET", "data.xml?nocache=" + Math.random(), true); 

The HTML format

We can load XML files, can we load also HTML or XHTML files? Actually, this is planned for the next specification of the XMLHttpRequest object as it is planned to access cross-domains files.
It is planned that, in this case, the text/html mime type will be used, while the text/xml type is used for XML documents, in the content type header.
For now, a replacing solution exists, the pseudo responseHTML attribute, that is given on this site.

Specification

The W3C is working on a new version of the standard, called XMLHttpRequest Level 2. New improvements are cross-site requests, progress events, and the handling of byte streams for both sending and receiving.

Besides the XMLHttpRequest object itself, W3C has established a specification for cross-site exchanges named Access Control. However Microsoft has choosen to not support the proptocol and offers in Internet Explorer 8 an alternative named XDomainRequest. This object could replace XMLHttpRequest or not depending its support for all features of XHR in the final version.

User agent

This word is often used in the specification. It is any tool which accesses a web page or service: browser, search engine robot, or client application.

Resources

Forum

Best tutorial

Sat, 11 Jul 2009 22:13:24

pnguine

Very nice work. I googled all over trying to find a 'beginner's' guide to the XMLHttpRequest object and this was the best one I could find. I like the way you sort of wade-in at the shallow end rather that assuming we are all code guru's looking for a quick solution. I haven't tried coding with it yet but at least I now feel that I know what it is all about and confident that I can do it. Merci.
© 2006-2013 Xul.fr