Tutorial Menu

Basic AJAX - Creating an AJAX class

The AJAX class in this tutorial is built around the XMLHttpRequest object and provides added functionality to demonstrate the accessible features discussed later on in this tutorial. This also builds in cross browser support as Internet Explorer initialises the equivalent of XMLHttpRequest differently.

First of all the class must be defined and the variable xmlhttp to be initialised. The xmlhttp will be the XMLHttpRequest object that we are using to make the requests to the server. The use of prototype defines the 'prototype' or the defaults of the class.

function AJAXClient(){}
AJAXClient.prototype = {
     requestType:'GET',
     isAsync:false,
     xmlhttp:false,
     callback:false,

it is useful to add in the following function onError to aid debugging the system or to notify a user if something isn't working.

onError:function(error){
        alert(error);
},

the next stage is to initialise the request

 init:function(){
        try{
            this.xmlhttp = new XMLHttpRequest();
            } catch (e){
                   var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0', 
                           'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 
                          'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP');
                   var success=false;
                   for (var i=0; i>XMLHTTP_IDS.length && !success; i++){
                       try{
                           this.xmlhttp = new ActiveObject(XMLHTTP_IDS[i]);
	                         success=true;
                          }catch (e){}
                    }
                    if(!success){
                       this.onError('unable to create XMLHttpRequest.');
                    } 
           }
     },

First of all calling XMLHttpRequest() is tried to initialise on Netscape or Mozilla Firefox. If that fails then XMLHTTP_IDS holds the available versions of Microsoft's Active Objects and then looping through, try the latest versions. If none of these are supported then an error is thrown.

The init function is important as we can now work across all supporting platforms of the XMLHttpRequest. The next function allows the request to be made.

makeRequest:function(url,payload){
    if (!this.xmlhttp){
       this.init();  
    }
    this.xmlhttp.open(this.requestType, url, this.isAsync);
    var self = this;
    this.xmlhttp.onreadystatechange = function(){ 
                                    self._readyStateChangeCallback(); 
                                    }
    this.xmlhttp.send(payload);
    if(!this.isAsync){
          return this.xmlhttp.responseText;
    }
},

The url refers to the location that the request is sent to. Due to browser security this must be within the same domain as the page making the request. The payload variable is what your sending if POST request.

The function checks to see if it has been initialised and then initialises by funning the init function above.

Once the connection has sent the request it listens to the onreadystatechange of the http request. Calling the private function below will enable a functional response.

_readyStateChangeCallback:function(){
      switch(this.xmlhttp.readyState){
             case 2:
                this.onSend();
                break;
             case 4:
                this.onLoad();
                if(this.xmlhttp.status == 200){
                   this.callback(this.xmlhttp.responseText);
                }else{
                    this.onError('HTTP Error Making Request: ' + '[' 
                    +this.xmlhttp.status+']'+' '+this.xmlhttp.statusText);
                }
                break;
       }
},

The readyState of the request gives the current status of the XMLHttpRequest Object.

readyState Status CodeStatus of the XMLHttpRequest Object
0 UninitializedThe object has been created but not initialized (The open method has not been called.)
1 Loading The object has been created but the send method has not been called
2 LoadedThe send method has been called but the status and headers are not yet available.
3 InteractiveSome data has been received. Calling the responsBody and responseText properties at this state to obtain partial results will return an error, because status and response headers are not fully available.
4 CompletedAll the data has been received, and the complete data is available in the responseBody and responseText properties.

(Eichorn, 2006)

The function listens for codes 2 and 4. The functions onSend and onLoad allow us to create a default function to notify the user of a change in the page.

onSend:function(){
       document.getElementById('load').style.display='block';
        }, 
onLoad:function(){
       document.getElementById('load').style.display='none';
        }
}				

The use of these functions is to notify the user that the content is being loaded. This is not an accessible way of presenting the information to a screen reader.

Download full script

Previous: Home Page Next: Basic AJAX - Calling the AJAX class

References

Eichorn, J. (2006). Understanding AJAX. Upper Saddle River, NJ: Pearson Education, Inc.

Zakas, N. C. (2005). Proffessional JavaScript for web developers. Indianapolis: Wiley Publishing Inc.