Web Applications with AJAX
 
Published: 13 Mar 2007
Abstract
Asynchronous JavaScript and XML (AJAX) is the ultimate web programming methodology for producing dynamic, rich web experiences and this article examines some of the important features of AJAX.
by Arindam Ghosh
Feedback
Average Rating: 
Views (Total / Last 10 Days): 35597/ 62

Introduction

As the Internet has become more mature, rich applications featuring responsive user interfaces and interactive capabilities have become increasingly popular. The capabilities represent a way to make programs easier to use and more functional, thus enhancing the user experience. Developers have used a variety of applications from companies, such as Macromedia, Microsoft, and Sun Microsystems, to add these capabilities in the past. However, Web applications have generally exhibited problems such as slow performance and limited interactivity, particularly when compared to typical desktop applications, noted Nate Root, research director for Forrester Research, a market analysis firm.

XML is a markup meta language that can define a set of languages for use with structured data in online documents. Any organization can develop an XML-based language with its own set of markup tags.

Cascading Style Sheets (CSS) is a W3C standard since 1996. CSS gives Web site developers and users more control over how browsers display pages. Developers use CSS to create stylesheets that define how different page elements, such as headers and links, appear. Multiple stylesheets can apply to the same Web page.

Document object model

The DOM, a W3C standard since 1998, is a programming interface that lets developers create and modify HTML and XML documents as sets of program objects, which makes it easier to design Web pages that users can manipulate. The DOM defines the attributes associated with each object, as well as the ways in which users can interact with objects. DHTML works with the DOM to dynamically change the appearance of Web pages. Working with the DOM makes Ajax applications particularly responsive for users.

JavaScript Released in 1995 by Netscape and Sun, JavaScript interacts with HTML code and makes Web pages and Ajax applications more active. For example, the technology can cause a linked page to appear automatically in a popup window or let a mouse rollover change text or images. Developers can embed JavaScript, which is openly and freely available, in HTML pages. Ajax uses asynchronous JavaScript, which an HTML page can use to make calls asynchronously to the server from which it was loaded to fetch XML documents. This capability lets an application make a server call.

The scope of web applications

It is true that applications like Photoshop and CAD will be incredibly difficult to implement within a web capable container, but do we really need that? I have never used either application and I do not believe either rank highly as an everyday tool for most people running around in big businesses.

The benchmark for web applications will always be Microsoft Office or rather, the fraction its functionality that is genuinely useful to a large number of users. Once you have a web-delivered application that delivers that sort of feature set, then a totally web-based desktop environment becomes a very practical option.

Ajax (Asynchronous JavaScript and XML) is the ultimate web programming methodology for producing dynamic, rich web experiences - it is one of the hottest technology topics around today, and it can be used in conjunction with all of the major server-side development tools, including Java, PHP, ASP.NET, etc.

Why AJAX?

Intuitive and natural user interaction

No clicking required

Mouse movement is a sufficient event trigger

"Partial screen update" replaces the "click, wait, and refresh" user interaction model

Only user interface elements that contain new information are updated (fast response)

The rest of the user interface remains displayed without interruption (no loss of operational context)

Asynchronous communication replaces "synchronous request/response model"

A user can continue to use the application while the client program requests information from the server in the background

Separation of displaying from data fetching Conclusion.

Technologies Used in AJAX

Javascript

Loosely typed scripting language

Allows programmatic interaction with the browser's capabilities

JavaScript function is called when an event in a page occurs

HTTP

XMLHttpRequest

DOM

API for accessing and manipulating structured documents

Represents the structure of XML and HTML documents

CSS

Allows for a clear separation of the presentation from the content and may be changed programmatically by JavaScript

Client-side: XMLHttpRequest

JavaScript object

Created within a JavaScript function

Adopted by modern browsers

Mozilla™, Firefox, Safari, and Opera

Communicates with a server via standard HTTP GET/POST

XMLHttpRequest object works in the background

Does not interrupt user operation

Server-Side: AJAX Request Processing

Server programming model remains the same

It receives standard HTTP GETs/POSTs

Can use Servlet, JSP, JSF

With minor constraints

More frequent granular requests from client

Response content type needs to be text/xml

Ajax mind share

Ajax has dominated the web application arena for quite sometime. The one strength Ajax has is that it is based on reliable web standards: The W3C gave us HTML, CSS, XML and DOM, and ECMA giving using JavaScript (or more technically correct EcmaScript). It is a wonderfully natural combination of technologies, especially for people involved in developing and supporting e-commerce applications.

Flash web applications

Flash is a capable platform that compares adequately to Ajax in terms of web application features. Behind the scenes, the workhorse is ActionScript which also has a direct lineage to EcmaScript. Flash supports XML, as well as transferring XML between the client and server. So a server-side component designed to talk to Ajax clients can also talk to Flash clients without modification.

Flash probably has the upper hand when it comes to the range of web applications it can implement. Flash applications will probably be more usable and user friendly than its Ajax equivalent, owing more to its past uses as a glitzy presentation interface.

Flash's disadvantages lie in its development tools. Yes, Macromedia Flash is known to be an extraordinary rich development tool, but it is expensive.

XUL web applications

XUL applications are going to be a hot topic in up coming years. One project in particular will offer the underpinnings, XulRunner. XUL applications have a stack load of useful components. Recently, a very interesting milestone has been added: rewrite Firefox as a XulRunner application.

XUL and Ajax

The technology behind XUL is almost identical to Ajax except the structure of the front end can be done in HTML, XUL, or a combination of both. Like Ajax, XUL uses JavaScript, CSS and DOM. XUL and Ajax are so closely aligned that switching between the two is far easier than trying to get your head around Flash.

XUL and Ajax score major points over Flash because it requires nothing more than a text editor to develop an application. (In terms of deployment, XUL probably would require a zip application like WinZip). Flash scores on its user interface capabilities, which easily outperform HTML and CSS.

Desktop widgets

Another web application area that has seen an incredible rise of popularity is that of desktop widgets. These are tiny applications that sit on the users desktop doing small tasks like checking for new mail, checking the local weather, football scores and the ubiquitous news ticker.

The surprising feature of these desktop widgets is that they are typically nothing more than HTML (or XML if you prefer) with CSS and JavaScript, along with a smattering of XML (or JSON) for data transfer; everything that comprises a typical web-based application.

The first step is to create an XML file with some data. We will call this file data.xml. It is a simple XML file and would most certainly be more complex in a real-world application, but for clarity our examples will be simple and concise.

Listing 1

<?xml version="1.0"   encoding="UTF-8"?>
   <root>
     <data>
This is some sample data. It is stored in an   XML file and retrieved by JavaScript.
     </data>
   </root>

 

Now let us create a simple web page containing some sample data. This is the page that all our JavaScript will be in and the page that users will visit to see the Ajax script in action. Let us call this file ajax.html.

Listing 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML   4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">
   <html lang="en" dir="ltr">
     <head>
       <meta http-equiv="Content-Type"   content="text/html; charset=iso-8859-1">
       <title>Developing Web Applications with Ajax -   Example</title>
     </head>
     <body>
       <h1>Developing Web Applications with
   Ajax</h1>
       <p>This page demonstrates the use of
   Asynchronous Javascript and XML (Ajax) technology to
       update a web page's content by reading from a remote
   file dynamically -- no page reloading
       is required. Note that this operation does not work
   for users without JavaScript enabled.</p>
       <p id="xmlObj">
       This is some sample data. It is the default data for
   this web page. <a href="data.xml"
       title="View the XML data."
   onclick="ajaxRead('data.xml'); this.style.display='none'; return
   false">View XML data.</a>
       </p>
     </body>
   </html>

 

Note that we link to the data.xml file for users without JavaScript. For users with JavaScript, the function “ajaxRead” is called, the link is hidden, and the link does not redirect to the data.xml file. The function “ajaxRead” is not defined yet, so if you test the example code above, you will get a JavaScript error. Let us go ahead and define that function (and another) so you can see how Ajax works. The following SCRIPT goes in your HEAD tags.

Listing 3

<script type="text/javascript"><!--
 function ajaxRead(file){
   var xmlObj = null;
   if(window.XMLHttpRequest){
       xmlObj = new XMLHttpRequest();
   } else if(window.ActiveXObject){
       xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
       return;
   }
   xmlObj.onreadystatechange = function(){
     if(xmlObj.readyState == 4){
        updateObj('xmlObj',
 xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
      }
     }
     xmlObj.open ('GET', file, true);
     xmlObj.send ('');
   }
   function updateObj(obj, data){
    document.getElementById(obj).firstChild.data = data;
   }
   //--></script>

That is quite a bit, so let us take this one piece at a time. The first function is “ajaxRead” – what we call from our “View XML data” link on the web page. In the function, we define an “xmlObj” variable – this will be the middleman between the client (user viewing the web page) and the server (the web site itself). We define this object in an if/else chunk.

Listing 4

if(window.XMLHttpRequest){
    xmlObj = new XMLHttpRequest();
 } else if(window.ActiveXObject){
    xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
 } else {
    return;
 }

This is just a test for the availability of different objects; some browsers implement the XMLHttpRequest object differently, so when we define “xmlObj” as our XMLHttpRequest object, we have to define it depending on what browser implementation is available. If no XMLHttpRequest object is available, we end the function with a “return” statement to avoid errors. Most of the time this check will return an XMLHttpRequest object; this particular code should work in almost every browser out there, with the exception of some older browsers (it works in IE 5.01, but will cease to function in Netscape 4).

Next is this block.

Listing 5

xmlObj.onreadystatechange = function(){
   if(xmlObj.readyState == 4){
       updateObj('xmlObj', xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
   }
 }
Real-Life Examples of AJAX Applications

Google maps

Google Suggest

Gmail

A9.com - Amazon.com search

Many more are popping everywhere.

Key Aspects of Google Maps

A user can drag the entire map by using the mouse.

The action that triggers the download of new map data is not a specific click on a link but a moving the map around. The user workflow is uninterrupted by the need to communicate with the server.

Behind the scenes

The map data is requested and downloaded asynchronously.

Usage cases for AJAX

Real-time form data validation

User IDs, serial numbers, postal codes, or even special coupon codes that require server-side validation can be validated in a form before the user submits a form.

Auto-Completion

Email address, name, or city name may be auto completed as the user types.

Master detail operation

Based on a client event, an HTML page can fetch more detailed information on data, such as a product listing.

Advanced GUI widgets and controls

Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes.

Refreshing data

HTML pages may poll data from a server for up-to-date data such as scores, stock quotes, weather, or application-specific data.

Server side notification

An HTML page may simulate a server-side push by polling the server for event notifications.

Conclusion

At the moment Ajax is all the rage. It makes sense for developers to learn how to produce Ajax-capable applications or front-ends. When XUL takes off, Ajax developers will find the migration much easier - it is just learning a new simple XML markup language. Ajax developers will also find the transition to writing desktop widgets easier too. In short, Ajax is hot and the skills it needs are reusable in other frameworks and applications.



User Comments

Title: Great Article   
Name: Raul
Date: 2007-05-10 9:38:23 AM
Comment:
Wonderful article.Easy reading and very interesting and informative
Title: S.E.   
Name: Anil pandey
Date: 2007-04-28 1:10:19 AM
Comment:
this artiale is realy very intresting. it simplyfies the use of AJAX in our projects
Title: call a serverside method from client site without postback using Ajax   
Name: Ritesh
Date: 2007-03-13 11:03:58 AM
Comment:
How i will call a serverside method from client site without postback using Ajax ? This is the main use of Ajax which is not described.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 9:21:10 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search