|
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.
var theData = '';
var theform = document.forms[0];
var thePage = window.location.pathname + window.location.search;
var eName = '';
Here we are declaring some variables to hold all of the form data theData, grabbing a reference to the current form theform, and obtaining the name of the current page. theData = '__EVENTTARGET=' +
escape(eventTarget.split("$").join(":")) + '&';
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. theData += '__VIEWSTATE=' +
escape(theform.__VIEWSTATE.value).replace(new
RegExp('\\+', 'g'), '%2b') + '&';
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. for( var i=0; i< i++ i++)
{
eName = theform.elements[i].name;
if( eName && eName != '')
{
if( eName == '__EVENTTARGET' || eName == '__EVENTARGUMENT'
|| eName == '__VIEWSTATE' )
{
}
else
{
theData = theData + escape(eName.split("$").join(":")) + '=' +
theform.elements[i].value;
if( i != theform.elements.length - 1 )
theData = theData + '&';
}
}
}
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. if( this.XmlHttp )
{
if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )
{
var oThis = this;
this.XmlHttp.open('POST', thePage, true);
this.XmlHttp.onreadystatechange = function()
{ oThis.ReadyStateChange(); };
this.XmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
this.XmlHttp.send(theData);
}
}
First, we make sure we have a valid XmlHTTPRequest object. Then, we check to make sure that the XmlHTTPRequest object is ready to make a new request.
Then, save a reference to the current object (CallBackObject). var oThis = this;
Open an asynchronous connection to the current page using the POST method. this.XmlHttp.open('POST', thePage, true);
As the state of our XmlHTTPRequest object changes, we want to be able to take various actions. We tell the object to call CallBackObject.ReadyStateChange() any time the state changes. this.XmlHttp.onreadystatechange = function()
{ oThis.ReadyStateChange(); };
Finally, send all the form data along with the request. this.XmlHttp.send(theData);
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. CallBackObject.prototype.ReadyStateChange = function()
{
if( this.XmlHttp.readyState == 1 )
{
this.OnLoading();
}
else if( this.XmlHttp.readyState == 2 )
{
this.OnLoaded();
}
else if( this.XmlHttp.readyState == 3 )
{
this.OnInteractive();
}
else if( this.XmlHttp.readyState == 4 )
{
if( this.XmlHttp.status == 0 )
this.OnAbort();
else if( this.XmlHttp.status == 200 &&
this.XmlHttp.statusText == "OK")
this.OnComplete(this.XmlHttp.responseText,
this.XmlHttp.responseXML);
else
this.OnError(this.XmlHttp.status,
this.XmlHttp.statusText,
this.XmlHttp.responseText);
}
}
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. CallBackObject.prototype.OnComplete =
function(responseText, responseXml)
-
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.
Listing 1 - CallBackObject.jsfunction CallBackObject()
{
this.XmlHttp = this.GetHttpObject();
}
CallBackObject.prototype.GetHttpObject = function()
{
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
CallBackObject.prototype.DoCallBack =
function(eventTarget, eventArgument)
{
var theData = '';
var theform = document.forms[0];
var thePage = window.location.pathname + window.location.search;
var eName = '';
theData = '__EVENTTARGET=' +
escape(eventTarget.split("$").join(":")) + '&';
theData += '__EVENTARGUMENT=' + eventArgument + '&';
theData += '__VIEWSTATE=' +
escape(theform.__VIEWSTATE.value).replace(new
RegExp('\\+', 'g'), '%2b') + '&';
theData += 'IsCallBack=true&';
for( var i=0; i<theform.elements.length; i++ )
{
eName = theform.elements[i].name;
if( eName && eName != '')
{
if( eName == '__EVENTTARGET' || eName == '__EVENTARGUMENT'
|| eName == '__VIEWSTATE')
{
}
else
{
theData = theData + escape(eName.split("$").join(":")) + '=' +
theform.elements[i].value;
if( i != theform.elements.length - 1 )
theData = theData + '&';
}
}
}
if( this.XmlHttp )
{
if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )
{
var oThis = this;
this.XmlHttp.open('POST', thePage, true);
this.XmlHttp.onreadystatechange = function()
{ oThis.ReadyStateChange(); };
this.XmlHttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
this.XmlHttp.send(theData);
}
}
}
CallBackObject.prototype.AbortCallBack = function()
{
if( this.XmlHttp )
this.XmlHttp.abort();
}
CallBackObject.prototype.OnLoading = function()
{
}
CallBackObject.prototype.OnLoaded = function()
{
}
CallBackObject.prototype.OnInteractive = function()
{
}
CallBackObject.prototype.OnComplete =
function(responseText, responseXml)
{
}
CallBackObject.prototype.OnAbort = function()
{
}
CallBackObject.prototype.OnError =
function(status, statusText)
{
}
CallBackObject.prototype.ReadyStateChange = function()
{
if( this.XmlHttp.readyState == 1 )
{
this.OnLoading();
}
else if( this.XmlHttp.readyState == 2 )
{
this.OnLoaded();
}
else if( this.XmlHttp.readyState == 3 )
{
this.OnInteractive();
}
else if( this.XmlHttp.readyState == 4 )
{
if( this.XmlHttp.status == 0 )
this.OnAbort();
else if( this.XmlHttp.status == 200 &&
this.XmlHttp.statusText == "OK" )
this.OnComplete(this.XmlHttp.responseText,
this.XmlHttp.responseXML);
else
this.OnError(this.XmlHttp.status,
this.XmlHttp.statusText, this.XmlHttp.responseText);
}
}
Listing 2 - Article.aspx<%@ Page language="c#" Codebehind="Article.aspx.cs"
AutoEventWireup="false" Inherits="AJAX.Article" %>
HTML
<head>
<script type="text/javascript" src="CallBackObject.js">
</script>
</head>
BODY
<script type="text/javascript">
var Cbo = new CallBackObject();
Cbo.OnComplete = Cbo_Complete;
Cbo.OnError = Cbo_Error;
function CheckUsername(Username)
{
var msg = document.getElementById('lblMessage');
if( Username.length > 0 )
{
Cbo.DoCallBack('txtUsername', '', true);
}
else
{
Cbo.AbortCallBack();
msg.innerHTML = '';
}
}
function Cbo_Complete(responseText, responseXML)
{
var msg = document.getElementById('lblMessage');
if( responseText == 'True' )
{
msg.innerHTML = 'Username Available!';
msg.style.color = 'green';
}
else
{
msg.innerHTML = 'Username Unavailable!';
msg.style.color = 'red';
}
}
function Cbo_Error(status, statusText, responseText)
{
alert(responseText);
}
</script>
<form id="frmAjax" method="post" runat="server">
<TABLE>
<TR>
<TD>Username:</TD>
<TD>
<asp:TextBox Runat="server" ID="txtUsername"
onkeyup="CheckUsername(this.value);"
OnTextChanged="txtUsername_TextChanged" />
</TD>
<TD><asp:Label Runat="server" ID="lblMessage" /></TD>
</TR>
<TR>
<TD align=left colSpan=3>
<asp:Button Runat="server" ID="btnCheckUsername"
OnClick="btnCheckUsername_Click"
Text="Check Username Availability" />
</TD>
</TR>
</TABLE>
</form>
</body>
</HTML>
History
- 2005-04-21
- Added links to Part 2.
- Updated source code download.
- Removed
abortCurrent argument from DoCallBack.
- Learned that
XmlHTTPRequest.open automatically aborts any current requests.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 42 (Total in Forum: 42) (Refresh) | FirstPrevNext |
|
|
 |
|
|
hello Bill,
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?
Thanks in advance.
Regards Hemant
Hemant Israni
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hemant Israni wrote: 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
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
In TextChange event of TextField I am setting value in a hidden field but when I try to get this value in OnComplete method I do not get it.
Any help??
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
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?
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi, First of all the article is great, i m using as an tutorial. using your concept, i m trying to make an uploading app.
Everything goes fine till the pointer reachs the server-side.
input=File object is null.
Can u guide with this. Thanx.
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
Error on the page in the line-by-line for DoCallBack:
You've got for( var i=0; i< i++ i++)
In the actual example code at the bottom it instead says (correctly):
for( var i=0; i
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
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
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
HTTP 1.1 mandates a two connection limit. See RFC2616 for more info.
On some browsers you can modify that limit, but it's not advised.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
AjaxProjects.com is a new directory...
Here you are...
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
Hazem TOrab
|
| Sign In·View Thread·PermaLink | 2.33/5 (3 votes) |
|
|
|
 |
|
|
(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?
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
This is great but Unfortunately I get a thead abort exception when I call reponse.end in your helper function. Any ideas?
Ronan Dodworth
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
You are using .NET 2.0 right? Any resolution to this? I know you can use HttpContext.Current.ApplicationInstance.CompleteRequest();
instead of Response.End()
However, it is still sending all the form databack.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
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 ?
Thanks in advance
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
I discovered that Opera (I use 8.5) do not support the XMLHttpRequest statusText property. I changed line 135 of the CallBackObject.js from
else if( this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK" )
to else if( this.XmlHttp.status == 200 )
and now the script works with Opera.
I do not know how this affects the functionality, probably the errorhandling will loose some functionality.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Whyer, Thanks for the catch. I have to plead guilty for not doing thorough testing on the CallBackObject. Your change shouldn't affect the functionality too badly I don't believe.
-Bill
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Very nice article. Maybe you are looking for a complete framework providing AJAX features like in this article while keeping ASP.NET server-side programming model, please visit:
http://www.comfortasp.de
Daniel
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
You inspired me to write an article of my own, based on your work. The link is here I hope you'll find the time to check it out.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Does this AJAX code support checkboxes?
I have implemented and it works great, all except checkboxes always are set as "true" regardless of their state. Perhaps I'm missing something?
Thanks. Jonathan.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
| | |