Object-Oriented AJAX with JavaScript

Introduction

My goal was to create a friendly, easy to use, and 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 and feel will be closely related. Because the code is tightly knit, the size of the .js file is an amazing 4.2 Kb. But, don't let the size fool you; sometimes little things pack a big punch. Well, enough said; 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

Object-Oriented AJAX with JavaScript

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, straightforward 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 usr. Because 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; it's your choice because they are class objects. They also can 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);

You'll need 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 your method to callback without any parameters, when the request status has changed. The fourth parameter is a boolean switch to make the individual request SYNC or ASYNC. You'll use 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. Doing 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! It's that easy? Yes, it is that easy! Object-oriented JavaScript is a beautiful thing.

Request Callback

During the retrieval of the request, the callback method of your Request object is called. It will be called more than 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. The possible states are as follows:
    • 0 = uninitialized
    • 1 = loading
    • 2 = loaded
    • 3 = interactive
    • 4 = complete
  • ResponseText: This is the response text, web page or XML content that is returned by the request.
  • Status: This is the status of the HTTP Request: 200 or 404.
  • URL: This is the URL that was requested.
  • UserObject: This is a free user object that was allowed to be passed around. Use it 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 requests 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!

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.
  6. .NET integration with callbacks.

Current Version

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.



About the Author

Adam Smith

Visit my website http://www.codevendor.com for all my latest new code releases and tutorials.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

  • Live Webinar Tuesday, August 26, 2014 1:00 PM EDT Customers are more empowered and connected than ever, and the customer's journey has grown more complex. Their expectations are growing and trust is diminishing as they may interact with multiple brands through web, mobile and social channels. Considering 70% of the buying process in a complex sale is already complete before prospects are willing to engage with a live salesperson -- it's critical to understand your customers and anticipate their needs.* …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds