19
Fri, Apr
5 New Articles

Use AJAX for Bright and Shiny Web Apps

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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 stands for Asynchronous JavaScript and XML. Don't worry about the XML part; you can use AJAX without having to write XML, although that is an option if you need it. The asynchronous part is important, though, as I'll explain later on.

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:

  1. Click the Contacts button.
  2. Type the search value or click on a letter of the alphabet to narrow your search.
  3. Click the Search button.
  4. Scan the list and click on the contact's email address.

Gmail has reduced this to two steps:

  1. You start typing the person's name or email address (even if it's just a guess).
  2. 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.

http://www.mcpressonline.com/articles/images/2002/Use%20AJAX%20For%20Bright%20and%20Shiny%20Web%20App1V4-11140500.png

(Click images to enlarge.)

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.

http://www.mcpressonline.com/articles/images/2002/Use%20AJAX%20For%20Bright%20and%20Shiny%20Web%20App1V4-11140501.png

Here's a summary of what happens:

  1. The user types a letter.
  2. The browser traps this event and calls a JavaScript function.
  3. 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.
  4. 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.
  5. When it's ready, the AJAX object retrieves the HTML output from the server-side script and invokes another JavaScript function.

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?

Remember that AJAX stands for Asynchronous JavaScript and XML. So there are three main components to AJAX technology:

Asynchronous

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

Javascript

AJAX requires the use of some Javascript to initiate an AJAX request to the server and to process the resulting response. In my next AJAX article, I'll explain how to write a set of self-contained Javascript that can be included as an external file in any of your Web pages to implement AJAX.

XML

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?

AJAX is very simple to implement. Since it requires only changes to the way you write client-side code, you can easily include AJAX in iSeries-based Web applications (CGIs or Java-based). You can package the code to implement AJAX as a Javascript include file and create a black box that you can include in any of your Web applications. You write the server-side components of your Web applications in the same manner, whether they are communicating with an AJAX object or not.

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. Meanwhile, here are some links to iSeries programs that use AJAX:

Gmail-like Example
Simple customer lookup example
To-Do List Example

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 28 years of experience on the midrange systems platform creating software for both green-screen and native Web environments.



Duncan Kenzie
Duncan Kenzie is President and CTO of ExcelSystems Software Development Inc. Duncan’s company is responsible for product development and technical support for BCD International Inc.’s (www.bcdsoftware.com) product line. Duncan has a BA in English Literature from the University of Waterloo, Ontario, and enjoys writing on a variety of subjects. Duncan is a frequent public speaker and has been writing articles about the midrange platform since 1985. He has also been involved in producing programmer productivity and business intelligence tools for 25 years and is the technical lead on products such as WebSmart, WebSmart PHP, and Nexus, leading System i Web tools.  Duncan still enjoys programming, and studies in leadership and self-improvement. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..
BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: