Click here to Skip to main content
13,042,630 members (80,516 online)
Click here to Skip to main content
Add your own
alternative version


77 bookmarked
Posted 24 Mar 2006

AJAX - A New Approach to Build Better Web-application

, 15 Sep 2010
Rate this:
Please Sign up or sign in to vote.
An article on AJAX


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:

var req = new XMLHttpRequest();

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

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:

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.

var req;
req = new ActiveXObject("Microsoft.XMLHTTP");
var url = "AjaxServer.aspx?PubID="+ID;
//Open a GET request to the URL"GET", url, true); 
//Actually Sends the request with a null body.
***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.

//Actually Sends the request with a null body.


The Properties

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:

//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:

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 != "")
    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:
function callInProgress(xmlhttp) {
    switch ( xmlhttp.readyState ) {
        case 1, 2, 3:
            return true;

        // Case 4 and 0
            return false;

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

if ( !callInProgress(xmlhttp) ) {
} 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.
<APPSETTINGS><ADD value="data source=cal-slcu2-196;
	Database=pubs;User=sa;PWD=sa" key="CONN_STRING" /></APPSETTINGS> 


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


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


About the Author

Technical Lead Patni Computer Systems Ltd.
India India
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 3 Pin
gg6720-Sep-10 22:37
membergg6720-Sep-10 22:37 
GeneralRe: My vote of 3 Pin
ChiranjibC16-Dec-10 19:07
memberChiranjibC16-Dec-10 19:07 
GeneralMy vote of 4 Pin
canozurdo17-Sep-10 2:21
membercanozurdo17-Sep-10 2:21 
GeneralMy vote of 2 Pin
kaschimer16-Sep-10 4:41
memberkaschimer16-Sep-10 4:41 
GeneralRe: My vote of 2 Pin
ChiranjibC16-Dec-10 19:11
memberChiranjibC16-Dec-10 19:11 
GeneralMy Vote of 2 Pin
kaschimer16-Sep-10 4:40
memberkaschimer16-Sep-10 4:40 
GeneralMy vote of 5 Pin
Eric Xue (brokensnow)15-Sep-10 11:21
memberEric Xue (brokensnow)15-Sep-10 11:21 
GeneralRe: My vote of 5 Pin
ChiranjibC16-Dec-10 19:03
memberChiranjibC16-Dec-10 19:03 
QuestionWill it works on firefox? Pin
Hiran Das22-Aug-07 23:21
memberHiran Das22-Aug-07 23:21 
Generalajax enabled web application Pin
veerbala4-Apr-07 18:46
memberveerbala4-Apr-07 18:46 
QuestionWhy? Pin
matthew_evans9-Jul-06 21:14
membermatthew_evans9-Jul-06 21:14 
AnswerRe: Why? Pin
Jawz-X13-Jul-06 5:05
memberJawz-X13-Jul-06 5:05 
AnswerRe: Why? Pin
ChiranjibC17-Sep-06 0:53
memberChiranjibC17-Sep-06 0:53 
GeneralRe: Why? Pin
jarle808-Feb-07 0:32
memberjarle808-Feb-07 0:32 
GeneralA few questions and suggestions Pin
varnk28-Mar-06 3:01
membervarnk28-Mar-06 3:01 
QuestionRe: A few questions and suggestions Pin
ChiranjibC29-Mar-06 8:00
memberChiranjibC29-Mar-06 8:00 
AnswerRe: A few questions and suggestions Pin
varnk29-Mar-06 9:20
membervarnk29-Mar-06 9:20 
GeneralNice but ... Pin
Marcin Smolka27-Mar-06 18:51
memberMarcin Smolka27-Mar-06 18:51 
GeneralRe: Nice but ... Pin
The_Mega_ZZTer9-Jul-06 13:11
memberThe_Mega_ZZTer9-Jul-06 13:11 
GeneralRe: Nice but ... Pin
Chayan21-Jan-07 23:36
memberChayan21-Jan-07 23:36 
GeneralAlread in Javascript Pin
newbegin25-Mar-06 18:27
membernewbegin25-Mar-06 18:27 
GeneralTODO Pin
Naveen Karamchetti24-Mar-06 2:51
memberNaveen Karamchetti24-Mar-06 2:51 
GeneralRe: TODO Pin
Amit Basu24-Mar-06 3:22
memberAmit Basu24-Mar-06 3:22 
GeneralRe: TODO Pin
RichardGrimmer25-Mar-06 2:15
memberRichardGrimmer25-Mar-06 2:15 
GeneralRe: TODO Pin
Shawn Poulson3-Apr-06 3:58
memberShawn Poulson3-Apr-06 3:58 
GeneralRe: TODO Pin
Islam94-Nov-07 0:57
memberIslam94-Nov-07 0:57 
QuestionWhat´s coming next? Pin
mbruenjes24-Mar-06 1:35
membermbruenjes24-Mar-06 1:35 
AnswerRe: What´s coming next? Pin
RichardGrimmer25-Mar-06 2:16
memberRichardGrimmer25-Mar-06 2:16 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 15 Sep 2010
Article Copyright 2006 by ChiranjibC
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid