Introduction

AJAX, if you haven’t already heard, stands for Asynchronous JavaScript And XML. If you’re unfamiliar with what AJAX is, I suggest reading AJAX: A New Approach to Web Applications by Jesse James Garrett. AJAX is a relatively new name for a set of technologies that have been around for quite some time. I recently signed up for a G-Mail account and was very pleased with its responsiveness and lack of obnoxious advertising. As a developer I thought that the site's performance was due to the lean layout and minimal use of graphics or WYSIWYG text editors. It turns out the G-Mail is a prime example of AJAX at work. After uncovering this revelation I decided to jump on the AJAX banding wagon and see what all the fuss was about.

At the heart of AJAX lies the XmlHTTPRequest (or XMLHTTP) object. This little doozy allows client side developers to initiate a request to a web page. For a nice reference on the XmlHTTPRequest object, see The XmlHTTPRequest Object. With a few lines of JavaScript, we can now initiate an Asynchronous request for a web page. Asynchronous means the request is made and the user doesn’t have to wait for the page to load or stare at an hourglass waiting for something to happen. The web request means we can now have seamless interoperability between client code (ala JavaScript) and server code (ASP.NET, JSP, PHP, etc.). If you didn’t say WOW you should at least be thinking it. With a little digging, you can find a number of examples on how to use the XmlHTTPRequest object. The goal of this article is to develop a framework for using the XmlHTTPRequest object in conjunction with ASP.NET. There are two things I’m trying to achieve with this framework:

Something easy for the client side developer to use to initiate an asynchronous HTTP request (which we’ll term a “Call Back”). This is the main focus of Part 1 of this article series. Something easy for the server side developer to integrate into their code (preferably without a lot of fancy or proprietary workarounds). We will focus on this in Part 2 of the series.

The Good Stuff

When I think about OOP and JavaScript the word “hack” comes to mind…but, I have created what I call the CallBackObject which we will go over in the remainder of this article (see Listing 1). The CallBackObject is simply a wrapper for the XmlHTTPRequest object. The CallBackObject allows the client side developer to initiate an asynchronous HTTP request (CallBackObject.DoCallBack) as well as provides a number of events for the developer to use to respond to changes in the state of the XmlHTTPRequest object. Let’s take it one method at a time.

Function CallBackObject()

This is the JavaScript constructor that is executed when a new CallBackObject is created like so:

var cbo = new CallBackObject();

The constructor creates a new XmlHTTPRequest object with a call to GetHttpObject() and assigns it to the member variable XmlHttp. I wish it were more exciting than that.

Function GetHttpObject()

The code for creating an XmlHTTPRequest object can vary depending on which browser is being used. Jim Lay posted the code that makes up the GetHttpObject method back in April 2002 (see, AJAX isn’t new). Essentially, IE browsers attempt to create an instance of the XMLHTTP ActiveX control, and Mozilla browsers create an XmlHTTPRequest object. If the browser doesn’t support XmlHTTPRequest, then the code does nothing.

Function DoCallBack(eventTarget, eventArgument)

This is where the magic happens. Remember, one of the goals of the CallBackObject is to make asynchronous HTTP requests that can be easily integrated into ASP.NET. ASP.NET coders should recognize the general format of this function, as it closely mimics the .NET doPostBack() JavaScript function that initiates server side events in ASP.NET. Let’s take it slow.

This is identical to doPostBack(), we are essentially telling ASP.NET which control is responsible for the Call Back. The escape is necessary to URLEncode any data posted to the server, the split and join return ASP.NET control ID’s to their proper form. It isn’t critical to understand why we are doing this to understand the JavaScript, I’ll cover this in more detail in Part 2 of this article.

The ViewState is that magical hunk of Base64 encoded text that makes web programmers’ jobs a lot easier. Unfortunately, the JavaScript escape function doesn’t handle the ‘+’ sign, so we have to manually encode it by substituting ‘%2b’ in its place.

theData += 'IsCallBack=true&';

This line lets the server side code know that the current request is a CallBack, initiated by the client side code. Otherwise, the server would assume it was a normal web request and might handle things differently.

Finally, we loop through the rest of the form elements (input boxes, check boxes, drop down lists, etc.) and append their names and values to our theData variable.

Now you might be wondering why we did all this. After all that processing theData now contains exactly the same information that is sent to the server whenever the “Submit” button is clicked on a form. We’re ready to make our asynchronous request to the server.

That’s it!!! We have successfully made an asynchronous web request using JavaScript… now what? Well, in most cases, you will be expecting some sort of response from the server after making your request. When the response comes back, you can process any data returned from the server. How will you know when the response comes back? That is where the ReadyStateChange() method comes in handy.

Event Handler ReadyStateChange()

The XmlHTTPRequest object has four main states/state codes, Loading-1, Loaded-2, Interactive-3, and Complete-4. To allow the client side developer to respond to each of those states, ReadyStateChange() receives the new state from the XmlHTTPRequest object, then raises the proper event.

A state code of 4 means complete but may not mean that things went according to plan. If a request was aborted then the state is changed to Completed-4, but the status is Unkown-0, so we raise an event for that as well. A successful HTTP request should yield a response of status 200-OK, anything else is considered an error and the OnError event is raised.

Event OnComplete(responseText, responseXML)

The OnComplete event makes the responseText and responseXML available to the client side developer. These values will depend on the data returned from the server side response.

Event OnError(status, statusText, responseText)

The OnError event provides some feedback on what may have gone wrong with the request. In this event you may re-initiate a request or indicate to the user that something went wrong.

But What Does it All Mean??

Well, that’s a lot to digest. AJAX requires an understanding of both client side and server side technologies, so it’s difficult to provide an example without delving into the server side aspect of things. For an explanation of the server side of things, read AJAX was Here Part 2 – ASP.NET Integration. See Listing 2 for the complete client side portion of the CallBackObject example. I’ll be covering it in more detail in Part 2, as well as showing you where the server side code fits in.

Conclusion

We’ve taken care of the bulk of the client side portion of things with the CallBackObject. Client developers can now make asynchronous requests without having to worry about too much of the details, but we still have some demystifying to do.

History

Learned that XmlHTTPRequest.open automatically aborts any current requests.

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.

Comments and Discussions

The code that you have mentioned in the AJAXWasHere-Part1.asp, was working fine in DOT Net 1.1 (Vs2003), but when we converted our application to DOT Net 2.0, it stopped working. Could you please let us know what the problems could be and what modifications would be needed to make it run with DOT Net 2.0 framework?

but when we converted our application to DOT Net 2.0, it stopped working.

How can the author possibly provide any assistance with such a nebulous description of the problem? "It stopped working"... The mind simply boggles...

Aren't you a programmer?

"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997-----"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

I am trying to learn how to simultaneously perform multiple async requests, (but with just using out-of-the-box Microsoft -- their ajax v1.0). For example, a search button that triggers code-behind in multiple panels/webparts (each is a source of info), each of which displays it's results as soon as it's specific search process is done (instead of displaying only when all of them are done).

Sorry, if it is a dumb question, but I am new to a lot of this. Is your example using Prototype?

any idea how many simultaneous requests can be fired async from the client browser to the server ?
i have played with it and was only able to get 2 requests handled at the same time at the server, although in the client code i fire like, 5 requests

This site will help you to find all the resource to learn and know all about Ajax technology, by providing you with the latest Ajax projects, latest Ajax tutorial, Ajax articles, Ajax Forum and Ajax news. \

I found this portal, it's about ajax technology it represents all the projects that implemented using ajax technology, and libraries that may help in creating ajax projects
http://www.ajaxprojects.com
Hazem Torab

(except mentioned gmail needs accout there?)
why i'm asking: it seems to me my pobox.sk also changed to any space technology
after this change many common browsing features like page-back or open (mail) in new window do not work properly
is it ajax related? or it is problem of concrete programmer?

added later:
i found there are alo google maps but they have the same problems mentioned before
do you know any "fully functional" example?

I am very happy with the code you have provided.
Just a quick qustion.
I am trying to package a callback in a Custom Control.
Can't seem to get it to work that well as yet.
Ps. Also how do ensure that if the client has to of the controls in the webform that the javascript functions are not repeated.
Is there anyway I can get and example of a custom user control using callback ?

I've added an extra if test that checks the type of the input. Normally checkbox controls are only included in an http request if they are checked, if they are not checked they are simply omitted from the form or querystring. Annoyingly, in javascript you have to use the .checked attribute, not the .value attribute, hence the special case.

Other than this little buglet, top quality work. I've successfully implemented this call back framework with the clientside code from here (http://www.momche.net/publish/article.php?page=acdropdown) and it produces a web component that is very very slick ...