Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET

AJAX - A New Approach to Build Better Web-application

Rate me:
Please Sign up or sign in to vote.
3.85/5 (28 votes)
15 Sep 2010CPOL6 min read 105.6K   636   77   28
An article on AJAX

Introduction

Asynchronous JavaScript And XML, or its acronym, Ajax, is a Web development technique for creating interactive web applications. It is used to submit a server request from a client using JavaScript and XML, without submitting the whole page. As a result, the whole process is exchanging a small amount of data, therefore is much faster and more responsive as a client-server based system. A nice implementation of AJAX can be seen here. If you write any alphabet into the textbox, a dropdown appears which is coming directly from the server, without submitting the whole page. The heart of AJAX is XMLHttpRequest object. The client can retrieve and submit the XML data directly in the background. To convert retrieved XML data into renderable HTML content, rely on the client-side Document Object Model (DOM) to read the XML document node tree and compose HTML elements that the user sees. AJAX is not a single technology like HTML, DHTML, etc. It is the combination of different technologies:

  • The XMLHttpRequest object is used to exchange data asynchronously with the web-server.
  • XML is commonly used as the format for transferring data back from the server, though any format could be used, like Plain Text, HTML, etc.
  • If XML is used as the transferring format, then DOM is usually used with a client-side scripting language like JavaScript to dynamically display and interact with the information presented.
  • XHTML (or HTML), CSS, for marking up and styling information.

Other Article

For design principles, Click here to Skip to main contentclick here.

A Brief History of XMLHttpRequest Objects

Microsoft first implemented the XMLHttpRequest object in Internet Explorer 5 for Windows as an ActiveX object. Engineers on the Mozilla project implemented a compatible native version for Mozilla 1.0 (and Netscape 7). Apple has done the same starting with Safari 1.2. In the proposed W3C standard, Document Object Model (DOM) Level 3 Load and Save Specification, similar functionality is mentioned. Now it becomes a de facto standard that will likely be supported even after the W3C specification becomes final and starts being implemented in released browsers (whenever that might be).

Creating the Object

XMLHttpRequest object creation differs for different browsers. For Safari and Mozilla, it creates like the following:

C#
var req = new XMLHttpRequest();

For the Internet Explorer 5.0 and above, pass the name of the object to the ActiveX constructor:

C#
var req = new ActiveXObject("Microsoft.XMLHTTP");

The methods of the objects control all operations, while its properties hold, among other things, various data pieces returned from the server, like xmlHttpObject.responseText contains the returned XML or string values from the server.

The Methods

The supported methods of XMLHttpRequest objects in Windows Internet Explorer 5.0 or later, Safari 1.2 and Mozilla are as follows:

MethodsDescriptions
abort() Abort the current request. If you call it on an object which isn’t processing a request (readyState 0 or 4) - weird things happen.
getResponseHeader("headerLabel")Returns the string value of a single header label
getAllResponseHeaders() Returns complete set of headers (labels and values) as a string
open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]) Assigns destination URL, method, and other optional attributes of a pending request
send(content) Transmits the request, optionally with postable string or DOM object data
setRequestHeader("label", "value") Assigns a label/value pair to the header to be sent with a request

Among the above methods, open and send methods are most important. Let’s discuss the open method from the application point of view.

C#
var req;
………………………
req = new ActiveXObject("Microsoft.XMLHTTP");
……………
var url = "AjaxServer.aspx?PubID="+ID;
……………
//Open a GET request to the URL
req.open("GET", url, true); 
//Actually Sends the request with a null body.
req.send(null);
***In the sample application, AjaxClient.aspx page is the user-interface and the AjaxServer.aspx is catering the data as per the user request. One important thing to note is AjaxServer.aspx page should not contain any HTML. You can test what will happen if that page contains HTML.

The first parameter “method” (see the above table for Open function) mentions whether the operation will be a GET operation or Post operation. In case of simple data retrieval, generally GET is used. Post is used when outgoing data packet size is more than 512 bytes and operation includes server side activities like insert, update, etc. Next comes the “url” parameter, this may be either complete url or a relative one. In this example, relative url is used. “asyncFlag” dictates whether the upcoming scripts will be processed immediately after the send method or not, means without waiting for a response or not. The last two are the “username” and “password” required if the “url” has any. The next important method is the send method, which actually sends the request with a body. For this specific application, it sends the request with a null body.

C#
[
//Actually Sends the request with a null body.

req.send(null);
]

The Properties

PropertyDescription
onreadystatechangeEvent handler for an event that fires at every state change readyState Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseTextString version of data returned from server process
responseXMLDOM-compatible document object of data returned from server process
statusNumeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusTextString message accompanying the status code

Here in the application, onreadystatechange is used as:

C#
//This is the event handler mechanism; In this 
//case "RequestProcessor" is the event handler.
req.onreadystatechange = RequestProcessor;

For this application, “RequestProcessor” is the event-handler for the client side. Now inside the event-handler (“RequestProcessor”) use readyState property to get various states. The value 4 is used to indicate the completion of certain processing. Now before processing, the result one should check the status or statusText to determine the success or failure of the operation. In this application, I did it in the following way:

JavaScript
function RequestProcessor()
{
//If the readyState is in the "Ready" state
    if(req.readyState == 4)
    {
        //Returned status code 200 means Everything is fine.
        if(req.status == 200)
        {
            //If responseText is not blank
            //req.responseText is actually a string written by AJAXServer.aspx by its 
            //"Response.Write("<bookpublisher />" + sbXML.ToString() + "");" method.
                        
            if(req.responseText != "")
            {
                populateList(req.responseXML);
            }
            else
            {
                clearSelect(publishedBooks);
            }
        }
    }
    return true;
}

****The object req is declared as page level variable as:
var req = new ActiveXObject("Microsoft.XMLHTTP");

Few Alerts

The URL of the request destination must be under the same domain as the client script belongs. The reason is XMLHttpRequest object adopts the same “Sandbox” as it were. On most browsers supporting this functionality, the page that bears scripts accessing the object needs to be retrieved via http: protocol, meaning that you won't be able to test the pages from a local hard disk (file: protocol).

A Real Life Problem

In AJAX, what will happen if the Network or Remote server is taking a break!!! Actually there are two major issues which are not solved “by default” in XMLHttpRequest object. They are:

  1. Dealing with Delay: If the network or remote server is taking its time, how does that relate to your AJAX application?
  2. Response Sequencing: Network (or server) latency may vary over time. That means responses may not return in the order they were requested. To handle the above two problems, the programmer need to write code in such a fashion that could be able to handle the above situations. One solution could be like this:
JavaScript
function callInProgress(xmlhttp) {
    switch ( xmlhttp.readyState ) {
        case 1, 2, 3:
            return true;
        break;

        // Case 4 and 0
        default:
            return false;
        break;
    }
}

Now before calling send(), I can look first to see if the object is busy, e.g.:

JavaScript
if ( !callInProgress(xmlhttp) ) {
      xmlhttp.send(null);
} else {
      alert("I'm busy. Wait a moment");
}

Browsers that Support Ajax

  • Microsoft Internet Explorer version 5.0 and above, and browsers based on it (Mac OS versions not supported)
  • Gecko-based browsers like Mozilla, Mozilla Firefox, SeaMonkey, Epiphany, Galeon and Netscape version 7.1 and above
  • Browsers implementing the KHTML API version 3.2 and above, including Konqueror version 3.2 and above, and Apple Safari version 1.2 and above
  • Opera browsers version 8.0 and above, including Opera Mobile Browser version 8.0 and above

Browsers that Do Not Support Ajax

  • Opera 7 and below
  • Microsoft Internet Explorer 4.0 and below
  • Text-based browsers like Lynx and Links
  • Browsers for the visually impaired (speech-synthesising, braille)
  • Browsers made before 1997

Sample Application Specific Requirements (Required Software and Settings)

Required software are:

  1. ASP.NET 2.0
  2. Microsoft-SQL Server 2000 with pubs database Settings required changing
  3. Changing DB connection string (“CONN_STRING” key) in web.config file.
XML
<APPSETTINGS><ADD value="data source=cal-slcu2-196;
	Database=pubs;User=sa;PWD=sa" key="CONN_STRING" /></APPSETTINGS> 

Acknowledgement

Thanks to www.ajaxblog.com which helped me to write this article and few previous Ajax-articles on CodeProject that helped me to build the basic understanding on AJAX.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Patni Computer Systems Ltd.
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
JBress20-Sep-10 22:37
JBress20-Sep-10 22:37 
GeneralRe: My vote of 3 Pin
ChiranjibC16-Dec-10 19:07
ChiranjibC16-Dec-10 19:07 
GeneralMy vote of 4 Pin
canozurdo17-Sep-10 2:21
canozurdo17-Sep-10 2:21 
GeneralMy vote of 2 Pin
kaschimer16-Sep-10 4:41
kaschimer16-Sep-10 4:41 
GeneralRe: My vote of 2 Pin
ChiranjibC16-Dec-10 19:11
ChiranjibC16-Dec-10 19:11 
GeneralMy Vote of 2 Pin
kaschimer16-Sep-10 4:40
kaschimer16-Sep-10 4:40 
GeneralMy vote of 5 Pin
Eric Xue (brokensnow)15-Sep-10 11:21
Eric Xue (brokensnow)15-Sep-10 11:21 
GeneralRe: My vote of 5 Pin
ChiranjibC16-Dec-10 19:03
ChiranjibC16-Dec-10 19:03 
QuestionWill it works on firefox? Pin
Hiran Das22-Aug-07 23:21
Hiran Das22-Aug-07 23:21 
Generalajax enabled web application Pin
veerbala4-Apr-07 18:46
veerbala4-Apr-07 18:46 
QuestionWhy? Pin
matthew_evans9-Jul-06 21:14
matthew_evans9-Jul-06 21:14 
AnswerRe: Why? Pin
Jawz-X13-Jul-06 5:05
Jawz-X13-Jul-06 5:05 
AnswerRe: Why? Pin
ChiranjibC17-Sep-06 0:53
ChiranjibC17-Sep-06 0:53 
GeneralRe: Why? Pin
jarle808-Feb-07 0:32
jarle808-Feb-07 0:32 
GeneralA few questions and suggestions Pin
varnk28-Mar-06 3:01
varnk28-Mar-06 3:01 
First of all, nice article. I have done some work with the XMLHttpRequest object as well. I was able to learn a few more things from your article that I had not known about before, so for my sake it was informative.


Considerring that this was posted as an ASP.NET article, I have a few suggestions that I had implemented in the past that may be helpful as well. I have not moved over to .net 2.0 yet, so my suggestions are solely based on .net 1.1.

1. On the server side I did something similar with a web control that is wrapped with an HttpHandler. The server control then fires an event to whatever page is hosting it and can then send the XML response back. DataSets work really well for the response in that just calling the WriteXml method and passing it the HttpResponse.OutputStream to return the request back to the client.

2. On the client side, I handled the events a bit differently. I used the ondatasetcomplete event. Not sure if this is any better or not than using onreadystatechange. I have seen some problems where the requests do sometimes come back out of order as well, so this event does not solve that problem. I have not found a decent work-around for this since I am using this method as a sequential player of images and associated data.

3. Databinding on the client side script also is a good way to implement display of results loaded without having to add much code to fill in the fields that may be used to display the data. You can do this using the datasrc and datafld of most controls to bind directly to the results returned by an XMLHttpRequest object.




-- modified at 9:02 Tuesday 28th March, 2006
QuestionRe: A few questions and suggestions Pin
ChiranjibC29-Mar-06 8:00
ChiranjibC29-Mar-06 8:00 
AnswerRe: A few questions and suggestions Pin
varnk29-Mar-06 9:20
varnk29-Mar-06 9:20 
GeneralNice but ... Pin
Marcin Smolka27-Mar-06 18:51
Marcin Smolka27-Mar-06 18:51 
GeneralRe: Nice but ... Pin
The_Mega_ZZTer9-Jul-06 13:11
The_Mega_ZZTer9-Jul-06 13:11 
GeneralRe: Nice but ... Pin
Chayan21-Jan-07 23:36
Chayan21-Jan-07 23:36 
GeneralAlread in Javascript Pin
newbegin25-Mar-06 18:27
professionalnewbegin25-Mar-06 18:27 
GeneralTODO Pin
Naveen Karamchetti24-Mar-06 2:51
professionalNaveen Karamchetti24-Mar-06 2:51 
GeneralRe: TODO Pin
Amit Basu24-Mar-06 3:22
Amit Basu24-Mar-06 3:22 
GeneralRe: TODO Pin
RichardGrimmer25-Mar-06 2:15
RichardGrimmer25-Mar-06 2:15 
GeneralRe: TODO Pin
Shawn Poulson3-Apr-06 3:58
Shawn Poulson3-Apr-06 3:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.