Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Object Oriented Ajax

0.00/5 (No votes)
1 Oct 2007 3  
Object Oriented AJAX class and objects structured for ease of use and maintainability for multiple requests.

Introduction

My goal was to create a friendly, easy to use, maintainable object oriented AJAX class. In creating this i have solved most of the issues with ASYNC and SYNC callbacks with multiple requests. Also I have made it easy to post data without having to worry about building a post back string. The code also uses some creative techniques to create object oriented style classes and objects like that found in C# style classes, so the look an fill will be closely related. Because the code is tightly knitted the size of the js file is amazingly 4.2 KB. But dont let the size fool you, sometimes little things pack a punch. Well enough said, lets jump into the API and see how this bad boy works.

Classes

Title: Connection
Namespace: System.Net.Ajax
Description: The main AJAX connection class for connecting to a webpage or xml resource.
Constructor(s) Description Return Value
Connection() Empty Constructor Connection Object
Connection(PageRequests) Constructor filled with System.Net.Ajax.PageRequests class object. Connection Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
Create() Internal method for creating the ActiveX Ajax or XMLHttpRequest object. New Ajax Object
Open() Opens the connection and retrieves the webpage or xml resource. Info Object
Properties Description Return Value
ActiveXObject Gets the current running ActiveX Ajax or XMLHttpRequest object. Ajax Object
PageRequests The PageRequests class containing all the Request Objects. PageRequests Object
Current The currently working request object. Current Request Object


Title: PageRequests
Namespace: System.Net.Ajax
Description: The PageRequests class for holding an array collection of Request class objects.
Constructor(s) Description Return Value
PageRequests() Empty Constructor PageRequests Object
PageRequests(Request) Constructor filled with System.Net.Ajax.Request PageRequests Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
AddRequest(Request) Adds a Request object to the array collection. Nothing
Properties Description Return Value
Requests The array collection of request objects. Array of Request


Title: Request
Namespace: System.Net.Ajax
Description: The Request class for holding all the properties and parameters for the request.
Constructor(s) Description Return Value
Request() Empty Constructor Request Object
Request(RequestMethod) Constructor filled with System.Net.Ajax.RequestMethod. Request Object
Request(RequestMethod, URL) Constructor filled with System.Net.Ajax.RequestMethod and URL. Request Object
Request(RequestMethod, URL, Callback) Constructor filled with System.Net.Ajax.RequestMethod and URL and Callback Method. Request Object
Request(RequestMethod, URL, Callback, Async) Constructor filled with System.Net.Ajax.RequestMethod and URL and Callback Method. Request Object
Request(RequestMethod, URL, Callback, Async, UserObject) Constructor filled with System.Net.Ajax.RequestMethod and URL and Callback Method and Async setting and optional UserObject. Request Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
AddParam(Parameter) Adds a Parameter object to the request object parameter array collection. Nothing
AddParam(Name, Value) Adds a name with value to the request object parameter array collection. Nothing
Properties Description Return Value
Method The HTTP request method GET or POST. string
URL The URL to retrieve. string
Params The parameters to send with the POST. Parameter Object Array
Callback The method to callback when the request is loading and complete. Method Reference
Async Whether the call should be async or sync. Bool
UserObject An extra free object to send back with the callback method. Any Type


Title: Parameter
Namespace: System.Net.Ajax
Description: The Parameter class for holding a name and value of a post parameter.
Constructor(s) Description Return Value
Parameter() Empty Constructor Parameter Object
Parameter(Name, Value) Constructor filled with a Name and Value. Parameter Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
Properties Description Return Value
Name The parameter name to post. string
Value The parameter value to post. string


Title: Namespace
Namespace: Window.Namespace, Namespace
Description: A custom object for handling the creation of namespaces in javascript.
Method(s) Description Return Value
Register(Name) Registers a namespace for use in javascript. Nothing


Title: RequestMethod
Namespace: System.Net.Ajax
Description: An enumeration for handling the HTTP Method.
Properties Description Return Value
Get For sending a Get HTTP Request. string
Post For sending a Post HTTP Request. string

Code Examples

Listed below are calls and code use for the following classes and objects. Like I said earlier I made this Ajax class to make it easier to understand and maintain, straight forward like you would expect from a langauage like C#.

A general good rule of thumb, is to start off by declaring what i'm going to be using. Since I have coded many constuctors, properties and methods, there are many ways to achieve the same goal with this AJAX class.

Declaration:

Example 1 (Constructor Driven):

var a = new System.Net.Ajax.Request("GET","default.html", Default_Callback, true);
var b = new System.Net.Ajax.PageRequests(a);
var c = new System.Net.Ajax.Connection(b);

Example 2 (Property Driven):

var a = new System.Net.Ajax.Request();
a.Method = "Get";
a.URL = "default.html";
a.Callback = Default_Callback;
a.ASync = true;
var b = new System.Net.Ajax.PageRequests();
b.AddRequest(a);
var c = new System.Net.Ajax.Connection();
c.PageRquests = b;

Most developers using my code will start off by creating their Request objects. You can create one or many its your choice, since they are class objects.

They can also be handled in an ASYNC call but in a SYNC order, if that makes any sense, all within the same request.

For Example:

var a1 = new System.Net.Ajax.Request("GET","default1.html", Default_Callback, true);
var a2 = new System.Net.Ajax.Request("GET","default2.html", Default_Callback, true);
var b = new System.Net.Ajax.PageRequests();
b.AddRequest(a1);
b.AddRequest(a2);

A little description about what the parameters and properties do of the request object. The first parameter is the HTTP Request Method, which can be either GET or POST. The second parameter is the URL to retrieve. You can add a querystring to it if you choose. The third parameter is the callback method pointer reference. This is the name of you method to callback without any parameters, when the request status has changed. The fourth parameter is a boolean switch for making the individual request SYNC or ASYNC. True for ASYNC and false for SYNC.

Adding Parameters to a Post Request

It is easy to add parameters to your post request by using the Parameter class object. Below is an example of adding postback values.

Example (Method 1):

var a = new System.Net.Ajax.Request("POST","default.html", Default_Callback, true);
a.AddParam("ID",1234567);
a.AddParam("Username","Adam");

Example (Method 2)

var a = new System.Net.Ajax.Request("POST","default.html", Default_Callback, true);
var p = new System.Net.Ajax.Parameter("ID", 1234567);
a.AddParam(p);

Example (Method 3)

var a = new System.Net.Ajax.Request("POST","default.html", Default_Callback, true);
var p = new System.Net.Ajax.Parameter();
p.Name = "ID";
p.Value = 1234567;
a.AddParam(p);

I made it easy to build params without having to know how the back end posting string works. So within seconds you can create reusable objects.

Opening a Connection

The guts and glory of this class is to open a Connection and get the data you need with an AJAX call. To do this with my class is very simple. Below I will show you the two ways.

Example 1 (Get Request Method)

var a = new System.Net.Ajax.Request("GET","default.html", Default_Callback, true);
var b = new System.Net.Ajax.PageRequests(a);
var c = new System.Net.Ajax.Connection(b);
c.Open();

Example 2 (Post Request Method)

var a = new System.Net.Ajax.Request("POST","default.html", Default_Callback, true);
a.AddParam("MyID","ABCDEFG");
var b = new System.Net.Ajax.PageRequests(a);
var c = new System.Net.Ajax.Connection(b);
c.Open();

Wow?, that easy! Yes, that easy! Object oriented javascript is a beautiful thing isn't it.

Request Callback

During the retrieval of the request, the callback method of your Request object is called. It will be called more then once with your status updates from the ajax request. The callback method is sent a custom method parameter containing many objects within it. I will list them here.

  • ReadyState - This is an integer value stating whether the request is ready and if you can access the ResponseText object. 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete
  • ResponseText - This is the response text, webpage or xml content that is returned by the request.
  • Status - This is the status of the HTTP Request, 200, 404
  • URL - This is the url that was requested.
  • UserObject - This is a free user object that was allowed to be passed around. Use to store whatever you want.
  • Complete - This is a boolean telling you if all the page requests have been completed that were in the PageRequests Array Collection.

Method Callback Example:

function Default_Callback(src)
{
    if(src.ReadyState==4)
     {
          if(src.Status==200)
          {
               alert(src.ResponseText);
   
               if(src.Complete)
                  {
                    alert("Finished All Page Requests");
               }
          }
     }
}

Any method you declare in your request object will be filled automatically with the object containing these items.

Putting it all together

<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
    
    var a = new System.Net.Ajax.Request("GET","default1.html", Testing, true);
    
    var a2 = new System.Net.Ajax.Request("POST","default2.html", Testing2, true);
    a2.AddParam("Test1","Yes");
    var b = new System.Net.Ajax.PageRequests(a);
    b.AddRequest(a2);
    var c = new System.Net.Ajax.Connection(b);
    c.Open();
    function Testing(src)
    {
         if(src.ReadyState==4)
     {
          if(src.Status==200)
          {
               alert(src.ResponseText);
          }
     }
    }
    
    function Testing2(src)
    {
         if(src.ReadyState==4)
     {
          if(src.Status==200)
          {
               alert(src.ResponseText);
   
               if(src.Complete)
                  {
                    alert("Finished All Page Requests");
               }
          }
     }
    }
</script>
</head>
</html>

This code demonstrates how diverse you can make the Connection. The example above does both GET and POST request in a SYNC(ASYNC) fashion, to two different callback methods. This was the power i needed in an AJAX class but couldn't find any out there. So i created it. I hope you enjoy my OO AJAX class!

Ajax Class Source Code

/* Copyright 2007 Codevendor.com */
// For registering namespaces

var Namespace = {
    
    Register : function(_Name)
    {
        var o = window;
        var x = false;
        for (var a = _Name.split("."); a.length > 0;)
        {
            var s = a.shift();
            if(a.length==0){ if(o[s]){x=true;} }
            if(!o[s]){o[s]={};}
            o = o[s];
        }
        
        if(x){ return 1; }
    }
}
//Create Namespaces----------------------------------------

Namespace.Register("System.Net.Ajax");
//---------------------------------------------------------

//Enumeration-----------------

System.Net.Ajax.RequestMethod = { Get:"GET", Post:"POST" };
//----------------------------

//Handles page requests in a collection----------------

System.Net.Ajax.PageRequests = function(){ return {
    Requests : null,
    
    //Gets the type of object---------------------------------------------

    GetType : function(){ return "System.Net.Ajax.PageRequests"; },
    //--------------------------------------------------------------------

    
    //Initializer---------------------------------------------------------

    Init : function()
    {
        this.Requests = new Array();
        if(arguments[0].length==1){ this.Requests.push(arguments[0][0]); }
        return this; 
    },
    //--------------------------------------------------------------------

    
    //Adds Requests to the collection

    AddRequest : function()
    {
        if(arguments.length==0 || arguments[0].GetType()!=
"System.Net.Ajax.Request"){ return; }
        this.Requests.push(arguments[0]);            
    }
    
}.Init(arguments);}
//Single Page Request

System.Net.Ajax.Request = function(){ return {
    Method : null,
    URL : null,
    Params : null,
    Callback : null,
    Async : false,
    UserObject : null,
    
    //Gets the type of object---------------------------------------------

    GetType : function(){ return "System.Net.Ajax.Request"; },
    //--------------------------------------------------------------------

    
    //Initializer---------------------------------------------------------

    Init : function()
    {
        switch(arguments[0].length)
        {
            case 1 : this.Method = arguments[0][0]; 
                     break;
            case 2 : this.Method = arguments[0][0]; 
                     this.URL = arguments[0][1]; 
                     break;
            case 3 : this.Method = arguments[0][0]; 
                     this.URL = arguments[0][1]; 
                     this.Callback = arguments[0][2]; 
                     break;
            case 4 : this.Method = arguments[0][0]; 
                     this.URL = arguments[0][1]; 
                     this.Callback = arguments[0][2]; 
                     this.Async = arguments[0][3]; 
                     break;
            case 5 : this.Method = arguments[0][0]; 
                     this.URL = arguments[0][1]; 
                     this.Callback = arguments[0][2]; 
                     this.Async = arguments[0][3]; 
                     this.UserObject = arguments[0][4]; 
                     break;
        }
        
        this.Params = new Array();
        return this; 
    },
    //--------------------------------------------------------------------

    
    //Adds Parameters to the parameter array collection

    AddParam : function()
    {
        switch(arguments.length)
        {
            case 1 : this.Params.push(arguments[0]); break;
            case 2 : this.Params.push(new 
              System.Net.Ajax.Parameter(arguments[0], arguments[1])); break;
        }
    }
    
}.Init(arguments);}
//Page Request Parameter Object

System.Net.Ajax.Parameter = function(){ return {
    Name : null,
    Value : null,
    //Gets the type of object---------------------------------------------

    GetType : function(){ return "System.Net.Ajax.Parameter"; },
    //--------------------------------------------------------------------

    
    //Initializer---------------------------------------------------------

    Init : function()
    { 
        if(arguments[0].length==2){ this.Name = arguments[0][0]; 
                                    this.Value = arguments[0][1]; }
        return this; 
    }
    //--------------------------------------------------------------------

}.Init(arguments);}
System.Net.Ajax.ActiveObject = 0; //For knowing what type of active X object.

//For handling ajax connections

System.Net.Ajax.Connection = function(){ return {
    
    ActiveXObject : null,
    PageRequests : null,
    Current : null,
    
    //Gets the type of object---------------------------------------------

    GetType : function(){ return "System.Net.Ajax.Connection"; },
    //--------------------------------------------------------------------

    
    //Initializer---------------------------------------------------------

    Init : function()
    { 
        if(arguments[0].length==1){ this.PageRequests = arguments[0][0]; }
        return this; 
    },
    //--------------------------------------------------------------------

    
    //Creates the active x object for use

    Create : function()
    {
        switch(System.Net.Ajax.ActiveObject)
        {
            case 0:
                if(window.ActiveXObject)
                {
                    try 
                    { 
                        System.Net.Ajax.ActiveObject = 2;
                        return new ActiveXObject("Msxml2.XMLHTTP");        
                    } 
                    catch(e) 
                    {  
                        System.Net.Ajax.ActiveObject = 3;
                        return new ActiveXObject("Microsoft.XMLHTTP");
                    }
                }
                else
                {
                    if(window.XMLHttpRequest)
                    {
                        System.Net.Ajax.ActiveObject = 1;
                        return new XMLHttpRequest();
                    }
                }
            
            case 1: return new XMLHttpRequest();           
            case 2: return new ActiveXObject("Msxml2.XMLHTTP");           
            case 3: return new ActiveXObject("Microsoft.XMLHTTP");
            default: break;
        }
        
        //No Ajax Object Found-----------

        System.Net.Ajax.ActiveObject = -1;
        throw "Missing a required ajax object.";
        return false;
        //-------------------------------

    },
    
    Open : function()
    {
        //Check if page requests has something------

        if(this.PageRequests==null){ return; }
        //------------------------------------------

        
        //Create Variables--------------------------

        var obj = this;
        var Data = "";
        //------------------------------------------

        
        //Create ActiveX----------------------------

        this.ActiveXObject = this.Create();
        //------------------------------------------

        
        //Get Request-------------------------------

        this.Current = this.PageRequests.Requests.shift();
        //------------------------------------------

        
        //Open Connection---------------------------

        this.ActiveXObject.open(this.Current.Method, this.Current.URL, 
                                this.Current.Async);
        //------------------------------------------

        
        //Create ActiveX Callback-------------------

        this.ActiveXObject.onreadystatechange = function() 
        {obj.OnReadyStateChange();}
        //------------------------------------------

        
        //Open Ajax Request---------------------------------------------------

        if(this.Current.Method=="POST")
        {
            this.ActiveXObject.setRequestHeader("Content-type", 
                                         "application/x-www-form-urlencoded");
               
            if(this.Current.Params!=null && this.Current.Params.length!=0)
            {
                for(var Param in this.Current.Params) 
                {
                    Data += (Data=="") ? this.Current.Params[Param].Name +
                         "=" + this.Current.Params[Param].Value : "&" +
                         this.Current.Params[Param].Name + "=" +
                         this.Current.Params[Param].Value;
                }
            }
            this.ActiveXObject.send(encodeURI(Data));
        }
        else
        {
            this.ActiveXObject.send(null);
        }
        //--------------------------------------------------------------------

    },
    
    //ActiveXObject callback

    OnReadyStateChange : function()
    {
        //Get Ajax objects for return-----------------

        var r = {};
        r.ReadyState = this.ActiveXObject.readyState;
        r.ResponseText = (this.ActiveXObject.readyState==4)?
                                      this.ActiveXObject.responseText:null;
        r.Status = (this.ActiveXObject.readyState==4)?
                                      this.ActiveXObject.status:null;
        r.URL = this.Current.URL;
        r.UserObject = this.Current.UserObject;
        r.Complete = (this.ActiveXObject.readyState==4 && 
                       this.PageRequests.Requests.length==0) ? true : false;
        //--------------------------------------------

        
        //Call Callback Method---------------

        if(this.Current.Callback!=null){this.Current.Callback(r);}
        //-----------------------------------

        
        //Loop For Many URLS

        if(this.ActiveXObject.readyState==4)
        { 
            if(r.Complete){ this.PageRequests=null; this.ActiveXObject.abort();
                            this.Current=null; }
            else{ this.Open();}
        }
    }
      
}.Init(arguments);}

Future Enhancements

  1. A new class for request header support. - Completed
  2. A new class for querystring support. - Completed
  3. ResponseXML and ResponseTEXT seperation. - Completed
  4. JSON / AJAX object passing.
  5. Error Handling and full null support. - Completed
  6. .NET integration with callbacks.

Current Version

October 1, 2007 - Version 1.0.1

Sept 10, 2007 - Version 1.0

Terms and Conditions For Use, Copy, Distribution, and Modification

THIS CODE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here