Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

AJAX - A New Approach to Build Better Web-application

0.00/5 (No votes)
15 Sep 2010 1  
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:

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:

Methods Descriptions
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
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.

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

req.send(null);
]

The Properties

Property Description
onreadystatechange Event handler for an event that fires at every state change readyState Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
status Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusText String 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("" + 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:
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.:

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.
<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 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.

A list of licenses authors might use can be found here