Introduction to AJAX by Charles Caplan AJAX (Asynchronous JavaScript and XML) has graduated from an Internet buzzword with few concrete implementations to a popular, stable technology that many websites use. Before you can enjoy all that AJAX has to offer, however, you need to learn how to create websites that take advantage of AJAX. This article explains how to do just that. I use both HTML and JavaScript code, and though any server-side technology works, I chose JavaServer Pages (JSPs) for these examples because it is the easiest server-side technology to set up on the System i. (For an introduction to AJAX, read "Next Generation Clients," May 2006, article ID 20524 at SystemiNetwork.com.) In addition to the handwritten AJAX code that I offer here, I discuss two free libraries that make developing easier: AJFORM and Prototype. Last but not least, I cover some common pitfalls to avoid and security concerns to be aware of as you get familiar with the AJAX application paradigm. By the time you finish this article, you should know how to create some simple web pages that take advantage of AJAX. Let's Dive In Put simply, AJAX lets a web page exchange information with a server without refreshing the entire page. In a typical web server transaction (one without AJAX), users click a link or a button to contact the server. The server then sends a response, and the browser displays the results as a completely new HTML page. With AJAX, however, users click the same link or button, but instead of refreshing the entire page, just a portion of the page changes, and the portion can vary based on the results returned. This refresh method is significant for several reasons. First, partial-page updates return less data, improving response time. Second, users don't need to wait for a full-page refresh (often accompanied by an eye-jarring screen blink), which provides a more pleasing browsing experience. Third, by not changing pages, your application environment stays within a single, constant HTML setting, which vastly simplifies your application architecture. Finally, partial refreshing lets you make the page more dynamic (based on results from the server) than possible with full-page refreshes. Sample Programs Three sample programs (available for download at SystemiNetwork.com/code) illustrate AJAX in action. As you work through those examples, you add external AJAX libraries to simplify common coding idioms. Progressing through the three samples gives you a hands-on knowledge of AJAX. The first sample document makes an AJAX call using only the functions included with your browser. It is an HTML form with a first name data-entry field and a submit button. The bottom of the page is blank but eventually displays the server's response (which is a simple JSP that can do anything), populated dynamically as a result of the AJAX transaction. It is this dynamic update that provides partial-page refresh, eliminating full-page HTML redisplay. The second sample document uses a library called AJFORM and though the end result is the same as the first example, the code is a lot more straight-forward. The third sample document uses a library called Prototype and also redisplays the user-entered data with the current date from the server. Manual AJAX Call Figure 1 shows a simple HTML document that contains a manual AJAX call that doesn't use external libraries. This example works as-is on both Internet Explorer and Mozilla- based browsers. The document contains an empty DIV tag at the bottom of the page with an ID of AJAXDiv (it can be called anything; this is just an example), which is where the result of the AJAX call is populated. The HTML form looks like a typical HTML form except that the onSubmit attribute calls a JavaScript function and returns false. The call to AJAXCall() starts the AJAX call (the method can also be called anything), and it returns false because if it does not, the URL changes when the Submit button is clicked, and the AJAX response is never shown. The JavaScript at the top of the document is where all the magic happens. When the page first loads, it instantiates a variable named xmlHttp with either the XMLHttpRequest or the Microsoft.XMLHTTP object, depending on the browser used. This is the object that actually makes the call to the server-side page behind the scenes. Fortunately, this object has the same methods no matter which browser is being used, even though the objects might be instantiated differently. When called, the function AJAXCall() invokes the xmlHttp object to send an asynchronous HTTP request to the server. In this case, the URL to transmit is given by the url parameter. AJAXCall() invokes the xmlHttp object's open method, passing it get and the URL. The first parameter can be either get or post and is used to decide whether the call to the URL in the url variable should use an HTTP GET or POST. Next, AJAXCall() sets onreadystatechange to the function named myResponseMethod, which is defined later in the code. This means that when various events occur throughout the AJAX call, a JavaScript method named myResponseMethod() should be called. Finally, AJAXCall() invokes the xmlHttp object's send method. If the request is a POST rather than a GET, this is where the contents of the POST request are specified. Because we are using a GET, this can be null. The next JavaScript function is named myResponseMethod() and is invoked multiple times throughout the AJAX transaction. The function checks for a readyState of 4, meaning that the AJAX transaction is finished, and then sets the contents of a div named AJAXDiv to the response of the AJAX call. It is important to always check for a readyState of 4. Otherwise, the method tries to update the div with the response before the AJAX call is completed, which could cause an error. If you run this example in a browser, you should see the bottom of the page populate with the contents of the first name entered and the current date of the server. Although this is a working AJAX application, there are some problems with using AJAX this way. When you want to make an AJAX call, you need to check which browser you are using. You have to repeat a lot of code if you use AJAX on many web pages. The manual AJAX call program does not handle errors gracefully. For example, if the page is not found or the page returns an HTTP error code, in a real-world application, you would need to handle the error. There are ways to handle errors in manual AJAX calls, but a lot of JavaScript code is required, and that is beyond the scope of this article. It would be nice to abstract the error handling to a separate library so that every time an AJAX call is made, errors could be handled in a standard way. In the manual AJAX call example, the HTML form is never actually submitted. Instead, the onSubmit handler calls the AJAXCall() method and returns false, making sure that the page does not change. HTML with AJFORM It would be nice if the HTML form elements could actually be used as part of the call, instead of the AJAXCall() method re-creating the form submission. Enter AJFORM, a free open-source AJAX toolkit that you can download from ajform.sourceforge.net. Using AJFORM to make AJAX calls offers several advantages over using the manual JavaScript that Figure 1 shows: AJFORM automatically detects which browser is being used and creates the correct XMLHTTP object for that browser. Errors are handled in a standard way, and the programmer can perform different actions based on different types of errors. AJFORM makes AJAX calls using actual form elements in the HTML form. When you submit a form using AJFORM, you can be sure that all form elements are passed to the behind-the-scenes page without intervention from the developer. Figure 2 shows an HTML page with an AJFORM call. Several differences exist between this and the manual AJAX call HTML, not the least of which is that you have to write much less code. The AJFORM code in this example has three lines of JavaScript, whereas the first example has 18 lines (not including comments). The ajform.js file instantiates objects, handles errors, and makes the actual AJAX call. To use AJFORM, include the JavaScript library ajform.js in your HTML form document, as shown in Figure 2. Next, invoke the ajform:getReturnData() function in the onSubmit attribute of your form. When the form is submitted, the AJFORM library makes the AJAX call to the URL specified in the form. When the server returns, AJFORM invokes a method called getReturnData(), which you must implement. In the example code that Figure 2 shows, getReturnData() updates a div named AJAXDiv, similar to the first example. AJFORM also greatly simplifies error handling. The getReturnData() function returns a status code and a status message, which holds error codes when an error occurs. Though the example doesn't illustrate error handling, the AJFORM documentation explains how to process various errors based on status codes that might be returned. As you can see, using a library such as AJFORM is much easier than writing all the JavaScript yourself. Prototype JavaScript Library The final example uses the free Prototype JavaScript library to make an AJAX call. Prototype can be downloaded from prototype.conio.net and does more than just AJAX calls. In addition to AJAX, Prototype offers a toolkit for class-driven development, which object-oriented programmers will appreciate. Figure 3 shows an example of an HTML form that uses Prototype. As with AJFORM, Prototype requires less code than the manual AJAX call, although it contains more code than the AJFORM call. However, the extra code gives you more flexibility. The main difference between AJFORM and Prototype is that Prototype requires no HTML form. Whereas AJFORM requires and uses HTML form elements, Prototype can make an AJAX call by calling any JavaScript method. This typically means that more code is required, but it also means that the developer now has the flexibility to make an AJAX call from either within or outside of an HTML form. The main JavaScript function used in this example is AJAXCall(), which defines the URL and associated parameters much like in the manual AJAX call example. However, executing the AJAX call with Prototype requires instantiating an AJAX.Updater object. To instantiate the AJAX.Updater object, pass an HTML element (AJAXDiv in this case) as an argument; this element eventually updates with the result of the AJAX call. You also pass the URL to call, as well as whether the call is an HTTP GET or POST, along with any parameters to include with the URL, and a method to call in case of an error. In this example, the error method is named reportError() and appears on the bottom of the page. This is only a simple example of how to use Prototype to make an AJAX call, but you can see how even though you write more code, you gain a lot of additional flexibility. Choose the Best Solution After trying these three methods, you might be wondering which solution is best for you. The answer depends on what level of functionality you require and how you plan on calling pages with AJAX. First, let me say that I do not recommend making manual AJAX calls without any external libraries unless you require functionality that the external libraries lack. Writing all the JavaScript yourself leaves you prone to errors and a lot of repeated code throughout your application. If you want to make AJAX calls using HTML form elements and you make only calls that involve forms, AJFORM might be the best solution. It provides easy AJAX calling with minimal code. Of the three methods, Prototype is the most robust AJAX development tool. Prototype can do more than AJAX calls, but AJAX functionality is what has made it popular. If you want to make AJAX calls inside or outside of HTML forms, or if you are looking for a way to move towards class-driven JavaScript development, Prototype might be the solution that you are looking for. In addition, projects such as Script.aculo.us from http://script.aculo.us extend Prototype to make your web applications even more dynamic. You should now be able to create functional AJAX applications. As with any technology, your understanding and coding proficiency improves as you gain hands-on experience. I encourage you to extend the examples as a learning exercise. You might also experiment with some of the other popular AJAX libraries; some will certainly suit your needs more than others. Before long, AJAX will be a part of your web skill set, and you will be creating pages that not only decrease load from the server but provide an enhanced user experience. Charles Caplan is a developer for a software company in the automotive lending industry and is certified by IBM and Sun Microsystems in XML and Java. You can e-mail Charles at chuck@chuckcaplan.com. Sidebar 1: AJAX Pitfalls and Security Concerns Browser compatibility. AJAX code runs differently in Internet Explorer than in other browsers (e.g., Firefox). Manually including the browser test code in all your applications is tedious and a maintenance burden. A better approach is to abstract the server-side calling code into a new method that can correctly handle all browsers. That's exactly what third-party libraries such as AJFORM and Prototype do for you. JavaScript settings. Users might access your site with their browsers' JavaScript disabled, though this situation is rare nowadays. If your web site relies too heavily on AJAX and other JavaScript technologies, your site will function incorrectly for such users. If you think that users might access your pages without JavaScript, you should either display a message stating that JavaScript is required to view your page, or design the site to use AJAX if it is available or full- page refreshes if it is not. This potential problem is of little concern in controlled environments, such as corporate intranets. Breaking the Back button. One disadvantage of AJAX is the potential to break the browser's Back button. If a single page uses AJAX to update repeatedly without changing to a new URL, the Back button becomes useless. If the user does click the Back button, your application could behave unpredictably. Keep this possibility in mind when you design an AJAX application, and test Back button operation before an end user does. Using AJAX too much. AJAX might be the current technology vogue, but that does not mean that you should use it everywhere. Having some pages employ AJAX might make sense, but using a full-page refresh might make just as much or more sense. Full-page refreshes are still commonplace in multipage applications. If each page asks the user for different pieces of information and can dynamically change based on the previous page's results, using AJAX might not be a good idea. Server security. AJAX has no inherent security features, so when you use it, you must take the same security precautions that you take with traditional web applications. For example, if you access pages with HTTPS to keep data secure, you should access your server-side pages via AJAX in the same way. In addition, many pages in traditional web applications cannot be accessed unless certain events occur first, such as a user logging in or another page being accessed first. AJAX pages should be secured in the same fashion, even if the only way they are accessed is with AJAX. You definitely do not want users to look at your HTML source code and see a URL that they could manually access without a security check. Ensure that all pages accessed with AJAX have the same security measures that a standard web application employs. Client security. End users need to be just as concerned with security as the server does. Because AJAX lets a server-side call happen based on any event, calls can happen behind the scenes without the end users' knowledge. You should use such AJAX features only with careful consideration and full disclosure. As an extreme example, imagine a page that makes a server-side call whenever users type a character into an input box. The server can record what the users type as they type it, but the users probably assume that anything that they type will not go to the server until they click the Submit button, as is true with a typical web application. In this case, users might feel that they have had their privacy invaded, because the server recorded every keystroke before the users even submitted the form. Make sure not to record such information without ensuring that your end users know and approve. C.C. Figure 1: Manual AJAX call