XmlHttpRequest object

Practically how do we incorporate Ajax into a web-page or web application.

According to the World Wide Consortium (W3C) working draft specification the XmlHttpRequest object is an Application Programming Interface (API) which “provides scripted client functionality for transferring data between a client and a server”. This means that it allows client based scripting languages such as JavaScript to transport Extensible Markup Language (XML) as well as additional text data between a web server and a client’s web browser. Consequently it allows web developers to use JavaScript to send XMLHttpRequest’s to a server. It is significant to note that it is this particular technology which allows a web-browser to connect and communicate with a server.

Using the XmlHttpRequest object a request is sent to the web server from the client and the data returned is typically in XML format. The next step entails the use of XSLT or DOM which is used to extract the essential data from the XML data initially returned from the web server. The figure below, demonstrates a piece of JavaScript code (taken from the W3C XmlHttpRequest specification) utilising the XmlHttpRequest object.

Additionally the XMLHttpRequest object, allows data transfer between the client and the web server to be carried out asynchronously, whereby multiple processes can take place at a single time. This means that a process does not have to be completed before another process is started. Put into context with Ajax web applications, HTTP requests are made with responses received in the background, hidden from the user (as there are no interferences with the state of the web page) while he/she continues to work. This is implemented by having an intermediary between the client (web browser) and the web server. Additionally in context specifically with the RSS reader application displaying feed data on the web page is done without any interference to the page and thus carried out asynchronously.

It entails:

  1. Creating a XMLHttpRequest object
  2. Opening a XMLHttpRequest connection providing a HTTP GET request
  3. Sending the request header

   var client = new XMLHttpRequest();
   client.open('GET','demo.cgi');
   client.send();

Further examples using the XMLHttpRequst object:

The following are a list of attributes and methods available in the XMLHttpRequest Object, taken from the W3C specificationGoogle tutorial and the Microsoft Developer Network Library

Constructing a new XMLHttpRequest object:

Example code:

    var oReq = new XMLHttpRequest()

Attributes

readyState (Readonly)

Indicates the state of the XMLHttpRequest object values include:

0 : UNSENT - The XMLHttpRequest object is initialised i.e. start point 1: OPENED - The open() method was called successfully 2: HEADERS_RECEIVED - Request successfully sent 3: LOADING - Currently receiving data 4: DONE - Data transfer has been completed /something went wrong during the transfer

onreadystatechange

Sets or retrieves an event handler for asynchronous requests

Example code:


     
     function reportStatus()
     {
       if (oReq.readyState == 4)
        alert('Transfer complete.');
     }
     
     var oReq = new XMLHttpRequest();
     oReq.onreadystatechange = reportStatus;
     oReq.open("GET", "http://localhost/test.xml", true);
     oReq.send();
 
 

status (Readonly)

Retrieves HTTP status code of the request – examples of HTTP status codes include 200: OK, 401: Access Denied and so on and these are basically response codes obtained from the originating server

Example code:

    
    var oReq = new XMLHttpRequest();

            if (oReq.status == 401)
             alert('Access denied.');
            else
             alert(oReq.responseText);

statusText (Readonly)

Retrieves a user friendly HTTP status of a request, providing text rather than a status code.

Example code:


    
    var oReq = new XMLHttpRequest();
    oReq.open("GET", "http://localhost/test.xml", false);
    oReq.send()
    if (oReq.statusText == "OK")
      alert(oReq.responseText);
    else
      alert(oReq.statusText);

responseXML (Readonly)

Retrieves the response from the server in XML format

Example code:


    
    var oReq = new XMLHttpRequest();
    oReq.open("GET", "http://localhost/books.xml", false);
    oReq.send();
    alert(oReq.responseXML.xml);

responseText (Readonly)

Retrieves the response from the server in text format.

Example code:

     
     var oReq = new XMLHttpRequest();
               oReq.open("GET", "http://localhost/books.xml", false);
               oReq.send();
               oReq.responseText;
           

Request methods

abort()

Cancels a current HTTP request

Example code:

var oReq = new XMLHttpRequest();
oReq.open("GET", "http://localhost/books.xml", false);
oReq.abort();

send([body])

Sends an HTTP request to a server, result is a response from the server Optional parameter body : String, array of unsigned bytes, or an XML object

Example code:

var oReq = new XMLHttpRequest();
oReq.open("GET", "http://localhost/books.xml", false);
oReq.send();

open(method, url, [asynch], [user], [password])

Initialises the connection with the server using a required HTTP method parameter (GET, POST, HEAD), required URL of the web resource, optional Boolean flag stating whether or not asynchronous communication is needed or not, optional username and password for authentication purposes upon connecting to the server.

Example code:

var oReq = new XMLHttpRequest();
oReq.open("GET", "http://localhost/books.xml", false);

setRequestHeader(headername,headervalue)

This method can set HTTP headers to a request. Parameters include a required header name and required header value.

Example code:

var oReq = new XMLHttpRequest();
oReq.open("POST", sURL, false);
oReq.setRequestHeader("Content-Type", "text/xml");
oReq.send(sRequestBody);

Response methods

getAllResponseHeaders()

Returns a list of response headers from the server

Example code:

function reportStatus()
{
  if (oReq.readyState == 4)
   alert('Transfer complete.');
}

var oReq = new XMLHttpRequest();
oReq.open("GET", sURL, false);
oReq.send();
oReq.onreadystatechange = reportStatus;

if(this.readyState == 3) {
  print(oReq.getAllResponseHeaders());

// response headers output:

Date: Sun, 24 Oct 2004 04:58:38 GMT Server: Apache/1.3.31 (Unix) Keep-Alive: timeout=15, max=99 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/plain; charset=utf-8

getResponseHeader(headername)

Returns the specified response header. Parameter is a required response header name.

Example code:

function reportStatus() { if (oReq.readyState == 4) alert('Transfer complete.'); }

var oReq = new XMLHttpRequest(); oReq.open(“GET”, sURL, false); oReq.send(); oReq.onreadystatechange = reportStatus;

if(this.readyState == 3) { print(oReq.getResponseHeader(“Content-Type”));

//specific response headers output:

Content-Type: text/plain; charset=utf-8

Last updated on 15 Jan 2009
Published on 15 Jan 2009