Use AJAX for Bright and Shiny Web Apps
Web development just got a whole lot cleaner!
by Duncan Kenzie
Published: November 14, 2005
AJAX is the hottest new technology to hit Web development in a long time. Well, it's not really new. The technology behind AJAX has been available for years now, but it has languished in relative obscurity until this year, when a company called Adaptive Path coined the term and wrote a seminal essay on the subject.
AJAX is hot because companies like Google, Yahoo, and Microsoft are exploiting it in powerful ways, demonstrating how it can provide richer and more interactive user experiences on the Web. Applications such as Google Mail, Google Suggest, and Google Maps all use AJAX to great effect. Other simple applications use AJAX also, such as Ta-da Lists, which lets you create and manage customized to-do lists.
So What's All the Fuss About?
Simply put, AJAX lets you create Web applications that respond immediately to user input or events. Suppose, for example, you have a form that requires users to type name and address information. In a non-AJAX application, you'd have them fill in all the details and then click OK to submit the form. Any errors would then be returned, along with the whole page contents, and shown somewhere on the page. This is analogous to green-screen programming, where the server has no interaction with the user until the Enter key is pressed. With AJAX, you can intercept user key strokes or mouse events as they happen and communicate with server-side code immediately. For example, as the user types a ZIP code, you could send that information to the server to do a lookup on city and state, find the info in a table, return it to the page, and update those form fields immediately in the page. This all happens seamlessly--without the page being entirely reloaded and without any annoying or confusing page flickers or clicks. In essence, this is event-driven client/server programming, where the "client" is a browser. So AJAX gives you all the benefits of client/server programming without the attendant headaches of software distribution issues; the client code is always up-to-date with the server code, because the client's just a browser.
How Google Has Popularized AJAX
Let's consider Gmail. Most of us are familiar with Web-based email programs, such as Yahoo's mail or hotmail. In these programs, when you compose an email, you can look up an intended recipient's email address by clicking a button that brings up a separate window with a list of contacts. You probably have many email addresses in your contacts list, and looking for a particular contact involves typing in a search value and clicking a search button or clicking on a letter. You then have to scroll through the subsetted list to find the contact you want and select it. So this involves at least four steps:
- Click the Contacts button.
- Type the search value or click on a letter of the alphabet to narrow your search.
- Click the Search button.
- Scan the list and click on the contact's email address.
Gmail has reduced this to two steps:
- You start typing the person's name or email address (even if it's just a guess).
- Google immediately responds to each character you type and pops up a dynamic list showing you the possibilities. If you see the one you want, you select it by clicking on it. If not, you keep typing.
How does Google do this? At first, I suspected they were loading my entire address list in the page, behind the scenes, and using a client-side script to traverse it. But that seemed unwieldy; it would mean that Google was reading and downloading all 500 of my contacts every time I went to look at my email, even before composing one. In fact, what
Google does is to employ AJAX technology in a very simple but powerful way. As I start typing characters in the To box, an AJAX call is made to the server to return up to 15 hits based on what I've typed so far. So in the example image below, you can see I've typed the letter m, and Gmail returns hits with M in them.
If I then type an i, the list is narrowed down further. Each time I type a letter, the browser runs a script to do an AJAX call to the server. The server immediately responds to the AJAX call and returns a new list of hits, which get placed in the page dynamically.
Here's a summary of what happens:
- The user types a letter.
- This function invokes an AJAX object that calls a server-side script (which could be a CGI program, a servlet, a PHP script, or any number of things), passing the user value as a parameter.
- The server-side script reads records from my Contacts list, finds hits, and then writes them as HTML output, just as it would write HTML to any standard page.
This function updates a specific portion of the page contents.
As the user types another letter, the whole process repeats itself.
Other Uses for AJAX
Google Maps is another example of AJAX put to good use. In this case, as you zoom in or out of a map, Google makes an AJAX call to retrieve a different map image and display it in your browser. This all looks seamless to you; there's no evident page refresh.
By the way, if you haven't already tried it, you should download Google Earth. This amazing application lets you fly through New York in 3D using satellite imagery, or explore the Grand Canyon, or investigate any other part of the earth. I suspect Google uses AJAX here, too, because advertisers such as hotels and restaurants can plot their points on Google's earth. Google uses AJAX to retrieve these ads from its database as you fly by.
Uses for AJAX in Your Own Business Applications
So you're probably wondering how you can improve your business applications with AJAX. Here are just a few ideas:
- Dynamic searches/lookups--Consider, for instance, the Gmail example or a customer lookup.
- Shopping cart updates--Immediately update a specific part of a Web page with an item's price or availability.
- To-do lists--An example of this on the Web is Ta-da.
- Customer information retrieval--You can update part of a page with customer details immediately upon selecting a customer number.
- Real-time error handling--You can validate user input immediately upon acceptance of that input (perhaps when the user tabs to another field or when that input field loses focus).
- Replacement of unwieldy drop-down boxes--If you have a drop-down box of values that typically contains more than 15 or 20 entries, it may be a good candidate to be replaced with an AJAX implementation. For example, a state abbreviation lookup or a phone number area code lookup will probably provide a better user experience. Try scrolling through a drop-down box that drops off the end of a Web page, and you'll see what I mean.
- Applications that require periodic background communication with a server--For example, a Web-based chat or messaging program may need to have the client poll the server at intervals of n seconds or minutes to see if any new messages are pending to be received by that client.
- The sending of "please wait" or "I'm busy" types of messages from the server to the user while a background activity takes place (and then the removal of those messages, of course)
- Pages that require several repeating lines of input
How Does AJAX Work?
"Asynchronous" describes the communication method between the browser and the server. It lets the browser and server talk to each other in the background while the user interacts with the page. You could deploy AJAX in synchronous mode (even though that's an oxymoron), but in this mode, the user must wait while the browser locks up and waits for a server response. For this reason, most implementations of AJAX are asynchronous. The AJAX object, which is a component of the browser, has properties that make it state-aware, so your code can monitor when it is in a ready state after making a server request. Once in a ready state, the AJAX object can notify some client-side script that it's time to update some page content.
This part is a little deceiving, because you don't actually have to use any XML at all to deploy AJAX. However, the AJAX object named XMLHTTPRequest (in Mozilla or Firefox) is the central piece in making an AJAX request and receiving the response, hence the X in AJAX. This object can return plain text (with or with HTML tags embedded) or XML that can be parsed. (Microsoft IE also has an object--with a different implementation but a similar name--that does the same thing).
Among the browsers that support AJAX are Microsoft Internet Explorer, Mozilla Firefox, Opera, Konqueror, and Apple Safari.
What About Server Workload?
Does using AJAX place an excessive workload on the Web server? In most cases, no. In fact, in many cases, the workload is often considerably less than it would be if an entire page of data had to be reloaded.
You can easily monitor server workload and performance by doing some simple user-interactivity tests. For instance, in the Gmail example, every keystroke initiates a server call. You might choose to implement this same approach for a customer lookup routine, allowing users to type a partial customer name and providing them with an (almost) instant response that returns a list of potential hits. You should probably watch over the shoulders of a couple of typical users to see how many letters on average they have to type in order to find the customer they want. Suppose the average number is three. That involves three server calls per lookup and a total of 45 database accesses (if we use Gmail's approach of returning 15 hits per keystroke). Is this a heavy server load? Well, from a database access perspective, it's negligible. How about Web server job activity due to more frequent CGI requests? My experience is that even a small iSeries can handle more frequent requests with no problem, too. However, if workload does become an issue, you can fine-tune your implementation. For example, instead of making a server call on every keystroke, just do one when the user exits the field (either by tabbing to another field or by moving the mouse).
Can You Implement AJAX on the iSeries?
In the next article, I'll explain the object that is the key component to AJAX technology and show some sample code you can use to start implementing it in your applications.
So consider using AJAX to make bright and shiny Web applications with real-time, event-driven functionality and with the coolness factor of Google!
Duncan Kenzie is President and CTO of BCD Technical Support, the development and support group for WebSmart a popular iSeries Web development tool, and Nexus, a portal product specifically designed for iSeries, i5, and AS/400 servers. Duncan has 29 years of experience on the midrange systems platform creating software for both green-screen and native Web environments.