Chapter 5. Getting the Most from AJAX

In this chapter

5.1 Goals of AJAX

5.2 Measuring Improvements

5.3 Promises and Problems of Combining AJAX with Other New Technologies

5.4 Summary

AJAX offers a whole world of new possibilities, but to reap the benefits, you must keep focused on your primary goals. In this chapter, we will cover some of the general objectives people have when implementing AJAX, as well as how to measure whether these objectives are ultimately met. To that end, we must also explore how these objectives enhance current applications. (To do so, Web applications built with standard techniques would need to be compared to applications built using AJAX.) Some tradeoffs may be necessary to use AJAX in conjunction with other technologies, because AJAX by itself won’t meet every application’s needs. Let’s get started!

5.1 Goals of AJAX

First and foremost, AJAX is about improving user experience; user experience improvements fall into two categories: making current tasks easier and making previously impossible tasks possible. Obviously, it is easier to focus on making current tasks easier. In Web development environments, this can be further broken down into two main goals: increasing interactivity and decreasing the time required to perform a task. In nonintranet cases, you may also have a related technical goal of reducing bandwidth use; by transferring less data to the browser, you can reduce page load times and improve the user’s overall experience.

5.1.1 Increasing Interactivity

One of the overall goals of adding any amount of JavaScript to a Web site is to increase its interactivity. Even without AJAX, you can provide content-sensitive information when the user moves over a link or validates a form without reloading the page. This extra interactivity provides more information to the users without overwhelming them. Using AJAX, we can build on this general process instead of focusing on adding extra static information; in other words, we can add extra information dynamically.

A good example of increasing interactivity is using AJAX to add a real-time search to a normal search form on your Web site. An example of real-time search is the Google Suggest application (www.google.com/webhp?complete=1&hl=en), which suggests possible search terms in a drop-down widget as you type your query; the widget would also indicate the number of results the search would return. Using Google Suggest to search for AJAX is shown Figure 5-1. Similar approaches can be used for any search application. The possibilities range from selecting a user on which to change permissions to picking a city to which to send a package.

Figure 5-1. Using Google Suggest to search for AJAX

image

You can also use AJAX to increase interactivity in ways other than search methods. One way is to use a scrollbar to move through a page of results instead of using the Web method of next page links. AJAX works well for items such as these because data is still loaded only as needed, just as with a normal table, but the later rows can be accessed much more quickly. Figure 5-2 shows a standard table paging widget, whereas Figure 5-3 shows a table using an AJAX scrollbar instead. The example in Figure 5-3 also allows columns to be sorted without loading the page. AJAX-based filtering could also be added to the table, making for a quick and natural data-browsing experience.

Figure 5-2. A standard table paging widget for a Web site, with each link causing a page reload

image

Figure 5-3. AJAX-based scroll table with new data being loaded by moving the scroll bar

image

AJAX opens up lots of new ways to increase interactivity because the extra data you’re showing can be loaded as needed. This becomes especially useful when working with medium-sized data sets, because you can see all the data without increasing the original page-load time or needing another reload to see the data. The biggest problem with increasing interactivity is that it is hard to measure, so increasing interactivity becomes most useful when looked at when addressing our secondary goal—decreasing the time required to perform the actions.

5.1.2 Decreasing the Time Required to Perform Actions

One of the biggest disadvantages of Web applications is that any multistep process becomes a multiminute process. On a fast connection, each page-reload connection adds two to five seconds of pure wait time as the next page is generated and downloaded by the browser, and on a slow connection, the waits can be double or triple that. Using AJAX to load in the new data allows us to remove these page reloads, making for a seamless experience with only a small one- or two-second wait for extra data.

There are lots of other cases where AJAX can be used to decease process times. They include using multistep wizards and reviewing and updating online content. Once you’ve found a task that takes a long time, such as moderating posts on a customer support forum, you look for the specific subtasks that take up the most time. In forum moderation, the problem is that each page reload takes a long time because you may be looking at 20 or 100 posts at once. Moderating posts requires one reload to start editing and then one reload to save your edit—a painful process. Other tasks, such as moving a post, are also slow because each page reload can make you lose your place in the list of posts.

For example, consider a conference-room booking system at a large company. After a room is chosen, each participant needs to be searched for and added to the booking so that he or she can receive a notification email. Because the company has over 100 employees, a select drop-down widget isn’t a good choice. Using it would greatly increase page load times because so much data would need to be preloaded. An extremely large drop-down widget would also be unwieldy to use.

The solution to this selection problem prior to AJAX was to add a search system to find each employee; the search system might even be put in a popup window to lower the amount of data to be reloaded, but no matter how it is implemented, adding each person becomes a 5- to 30-second process. This clunky interface isn’t a problem when adding 1 or 2 people, but it becomes unbearable when adding 20 or more. An AJAX approach allows the search to happen using a real-time search. The interface would look much like Google Suggest in Figure 5-1, displaying employees’ names instead of search terms. In this case, by using AJAX, we make adding 20 employees a 1-minute process instead of a 5-minute process.

Using AJAX, you speed up the process by adding in-place editing and by using drag-and-drop to move a post. In-place editing works by creating a text editing box without reloading the page. Because the content is already displayed, no request needs to be sent to the server to start an edit. At the end of the process, the changes are transparently saved while the user moves on to editing the next post. An example of using inline editing is shown in Figure 5-4. Drag-and-drop moving of posts is also a large time-saver, mainly because it’s much easier to see the target location on your normal post-browsing screen than it is to see it in a list of post titles that a non-AJAX process would be forced to use.

Figure 5-4. In-place editing

image

One of the things that make reducing task time such a great AJAX implementation goal is that it is easily measurable. All you need to do is sit down and perform some of the tasks and track the amount of time they take to complete. Depending on the tasks, you can even add timers to the application to record normal-use data. Once you have these baseline numbers, you can create specific targets for your AJAX implementation. Combined with further tracking after you’ve created an AJAX implementation, you can obtain data to decide how effective your enhancements have been. With a real and repeatable measurement, the effectiveness of AJAX moves from guesswork to simple math. You can even use this process-time measurement to improve on your current AJAX use, swapping out techniques or adding in prefetching to make a process take less time.

5.1.3 Reducing Bandwidth Use

Reducing bandwidth use can be a useful goal in some AJAX implementations because a smaller amount of data takes less time to transfer, providing the user a more seamless experience. If you’re paying for hosting, reducing bandwidth use can also be an effective way to save money. However, if you’re using your application on an internal network, this may be a goal that doesn’t matter at all because the fast network keeps load times low no matter how much data you transfer.

Bandwidth use is easy to measure; the related metrics are always easier to use than subjective comparisons. Of course, unlike the measurement of time to perform a task, bandwidth use isn’t a number that you always want to see decrease as a whole. Reducing the amount of data loaded in the initial page load can be useful, especially if that data is seldom used and can be easily loaded as needed. However, in some cases, the best user experience is achieved by preloading data and increasing the overall bandwidth use.

You can preload data directly during the initial page load or by using AJAX call, but you’ll find that using AJAX is beneficial as long as the data isn’t needed immediately. AJAX preloading can happen after the page is loaded, making it less noticeable to the user. It can also be tied to the beginning of a task that will use it. This is especially true when browsing large data sets because they generally have consistent access patterns that can be discerned by monitoring the users of the applications.

AJAX doesn’t have guaranteed bandwidth reductions and, in some access patterns, it will likely use more bandwidth. This is especially true when you’re performing event-driven AJAX requests. Each request may be small, but a search for each keystroke can quickly add up. These effects may be reduced by limiting the number of events to one per time period, but the effects will still build up over time. Your goal should be to make each request as small as possible, while realizing that these bandwidth reductions may be eaten up by the greater quantity of requests and by using prefetching to make a highly interactive interface.

5.1.4 Creating Rich Applications

Our first three goals focused mainly on making enhancements to current Web applications; however, AJAX also gives us the possibility to create an entirely new class of Web applications. When creating rich applications, developers have the goal of making them work as much like native applications as possible, while trying to keep Web development’s advantages in ease of deployment and implementation. In addition, rich applications development still has the goal of increasing the interactivity of the application and decreasing the time needed to perform actions, although the design and implementation of these goals may be different.

Because you’re not taking a current application and fixing slow spots, you don’t have the baseline metric of a standard Web application. Instead, you have to compare your application against its native equivalent. This can be challenging because native applications can use large persistent data stores to reduce the number of slow interactions, whereas AJAX applications are limited to smaller session-based caches. Depending on how data-intensive the task is, you may be unable to match the performance of a native application, so you’ll need to focus on different usage patterns that will hide this problem. The easiest native applications to mimic are those that deal with a large dataset that isn’t stored fully on the local client; because the data-access speeds are similar, the Web application needs to compete only on the quality of its user interface.

Many rich applications use more bandwidth than their standard Web application counterparts because they rely heavily on prefetching data to give a seamless user experience. This makes rich applications better suited for internal deployments where a fast network and the lack of bandwidth charges remove bandwidth reduction as a necessary goal.

The decision to build a rich application instead of an enhanced Web site should not be taken lightly. Rich applications work best when they are targeting the tasks performed by a native application. Email clients, RSS readers, and reporting applications are good examples of native applications that are easy to mimic. That being said, services normally provided by Web sites, such as shopping at an online store or displaying product information, don’t translate well to rich applications. These tasks are better suited to an enhanced Web site where only the slow, complex tasks are replaced with AJAX versions.

5.2 Measuring Improvements

Measuring the time it takes to complete a task is one of the most useful metrics when looking at the success of an AJAX implementation. The actual measurement process is broken down into three simple steps:

1. Identifying a task’s starting and ending points

2. Adding instrumentation to measure the starting and ending times

3. Combining multiple data points into useful information

Deciding which tasks to measure is generally a simple process; you need only find the areas in the application about which users always complain. If a process is slow and clunky, it’s a good target for AJAX and therefore a good target for measurement. After choosing the task you need to measure, identify its starting and ending points. It’s important that you measure the entire process. You don’t want to focus on page loads or the technical pieces, but actual steps taken by the user. If the process is complex, you may find it useful to watch users in action to see how things are actually done.

Once you’ve identified the start and end points, you need to add instrumentation. In most cases, you can do this by making some simple AJAX requests to a recording script. One call marks the beginning of the process, and a second records the ending. In our example case, we’ll be recording the time it takes to select a user to edit, as shown in Figure 5-5. This example is extremely artificial, but useful, because the goal is to show how to instrument a process, not how to build an AJAX user editor.

Figure 5-5. Selecting a user

image

The breakdown of this task is as follows: Load the page, search for a user, and then select the user from the results. The start of this task could be considered the loading of the page or the clicking of the Search for User button. In our example, we use the clicking of the Search for User button because it will help reduce the amount of variance in our measurement. The end of the process occurs when the selectUser JavaScript function runs; in an actual implementation, this would either redirect us to a user editor or populate an editing form below the selection section. A unique ID will also need to be created so that the start and end times can be matched together, but as long as the client is making only one request at a time, this ID can be created and stored in our data-storing script.

To implement the instrumentation, we will be using our basic HttpClient XMLHttpRequest wrapper. We will be making an AJAX call to process.php at the beginning and the end of the process. process.php will store this data in the session, and then process.php’s endProcess function will match it with a second end request that happens when the process is complete. A simple report (see Figure 5-6) can then be run to see how long each attempt to select a user took. The data storage is basic in this implementation and would need to be replaced with a database if you wanted to collect data from multiple machines.

The reusable parts of the measurement process are the process.php storage script shown in Listing 5-1 and the Monitor JavaScript class shown in Listing 5-2.

Listing 5-1. process.php

image

image

Listing 5-1 uses a PHP session to store its data, so the script starts out by setting this up. We start the session on line 2 and then set some default values on lines 4–9. Lines 12–41 define three functions, one for each of the actions the script can take. The startProcess function (lines 12–20) first checks if we have a current ID stored in the session; this check allows us to ignore multiple start requests for the same process. If there isn’t a stored ID, startProcess stores the current time, creates a new random ID, and then puts this data, along with the process name, into the session. The endProcess function (lines 22–26) stores the current time as the end time and then clears out the ID to allow another process to start. These two functions provide the basic data-gathering capabilities of the script.

The third function, printStats (lines 28–41), creates a table that provides basic reporting. It loops over the data stored in the session and creates an HTML table. While doing this, it uses the start and end times to calculate how long each process took. The output from this function is shown in Figure 5-6. Lines 43–53 control which of the functions is called. The function to call is selected by the GET variable action. On the HTML side, JavaScript monitoring code makes AJAX requests to process.php to store the usage data.

Figure 5-6. A simple report of how long attempts to select a user took

image

Listing 5-2. Monitor.js

image

The monitor class is quite simple; it sets up an instance of HttpClient for asynchronous operation in its constructor (lines 3–7) and then defines two functions. The first startProcess sends a request to process.php, which triggers its startProcess function. The second function, endProcess (lines 13–16), sends a similar request to process.php, but this time, the AJAX request triggers the matching endProcess PHP function. The main purpose of this class is to make it easier to instrument application pages, so it takes care of the boilerplate code for you. It is also a good place to add other methods if you find yourself needing to collect other data, such as which actions a user performs.

Now that we have a basic instrumentation framework set up to collect process times, we need to add it to a script. The process-time data can be useful in AJAX-driven pages to collect data that is generated by changes you are making. It is also useful in non-AJAX pages to help measure slow processes and to find ones that should be updated. Data collection like this can also be useful in making decisions on what data to prefetch, but normally, more data than simple timings is necessary because you need to identify which actions the user is most likely to perform. Listing 5-3 shows a simple user-selection script that uses the Monitor JavaScript class from Listing 5-2 to record how long each selection takes.

Listing 5-3. selectUser.class.php

image

The actual searching takes place in a related class, selectUser. This class does all its searching against an array to keep the example as simple as possible, but in most cases, this process would be database-driven. The class has a single method search (lines 15–24), which takes an input. The method then case-insensitively checks this input to see if it exists in the array of any of the users stored in the class. Last, the method builds an array from the matching results and then returns this array. The HTML user interface is built in Listing 5-4, which uses the selectUser class to handle POST requests to the page.

Listing 5-4. selectUser.php

image

image

The script starts with some basic setup; then, line 6 includes the XMLHttpRequest wrapper, and line 7 includes the JavaScript Monitor class. Line 9 creates an instance of the Monitor class so that we can easily call startProcess and endProcess throughout the page. Lines 10–13 define the JavaScript function that is called at the end of the user-selection process; this function just outputs a selected message and then runs endProcess. Lines 20–25 provide the basic HTML UI of the page; this is a form that POSTs its results to the current page. The search input box runs a start process when you click it to start entering your search term.

Lines 27–40 perform the search after the form is POSTed to the page. An instance of the selectUser class does the actual searching. The results from this search are then looped over, creating a radio button for each result. An onclick action is added to each radio button, which calls the selectUser function defined in lines 10–13.

The basic workflow of this page is shown in Figure 5-7.

1. The user clicks the Search input box, sending a startProcess request.

2. The user clicks the Search for User button, POSTing the form.

3. The script uses the name sent in the POST request to build a list of radio buttons from which the user can select a specific user.

4. The user clicks a radio button, sending an endProcess request.

Figure 5-7. Workflow measuring how long it takes to select a user

image

Data collection is an important first step to making good decisions about how and when to implement AJAX. If the user-selection process is already fast, it doesn’t make sense to spend time adding AJAX to it; instead, you’ll want to find a different process to upgrade. If the process is slow, you can build an AJAX version that adds instrumentation to it and then obtain real numbers on how effective the process is. Ultimately, you may find that an AJAX version of the form won’t give you the increased speed that you need, because searching by name doesn’t scale to the number of users in your system; instead, your best results might be accomplished by limiting the search results using other criteria, such as department or job title.

5.3 Promises and Problems of Combining AJAX with Other New Technologies

As you work with AJAX, you may hear of related technologies that you can use with AJAX. They fit into two main groups: mature technologies that are widely available in many browsers today, and new technologies that are available only on a specific browser. The mature technologies include Java and Flash. (Flash is the most important because its plug-in is widely installed, and its design is optimized for providing interactive elements and animations to Web sites.) Java can also be used to add interactivity to sites, but its popularity has waned over the past five years, and it’s no longer installed by default everywhere.

5.3.1 Combining AJAX with Flash

Flash makes a good partner with other AJAX techniques because it provides a number of features that are not available with pure JavaScript. These include a canvas on which images can be added and positioned and a drawing API that can be used for creating graphics. In addition, Flash has the ability to stream video and sound, and it includes support for vector animations. The biggest drawback of Flash is that it adds a new, separate development environment, and although you can make calls between the JavaScript on your page and the ActionScript of your Flash movie, it’s not tightly integrated with the rest of your page. Flash also has a different look than the rest of the elements on an HTML page, which makes it hard to deliver a consistent feel and operation when using it for small elements within a bigger picture.

The drawbacks of Flash—poor JavaScript integration and a different look and feel—are not insurmountable, but they do lead many people to pick a complete Flash solution when they need to do anything complicated. This helps control complexity, but it leaves you fully tied to a single vendor and means that you have to use Flash remoting for your communications layer instead of AJAX. Adding Flash to your AJAX application gives you the ability to support many graphical tasks that would be impossible without it, but be prepared for a more complex design and debugging process.

5.3.2 Scalable Vector Graphics (SVG)

The new technologies in the browser world are not as widely deployed as Flash, and some, like Microsoft’s Extensible Application Markup Language (XAML), have had only beta releases. They do have the benefit of being fully integrated into the browser, making them fully scriptable with JavaScript and available as first-class elements on Web pages. Scalable Vector Graphics (SVG) is a new W3C standardized language for creating vector graphics. It has many of the same features as Flash, allowing for animations and interactive graphical elements to be added to the page. SVG avoids many of Flash’s problems because it uses JavaScript for scripting; in addition, it can be embedded directly into an HTML page and modified just like any other element.

SVG’s biggest problem is that browser support has been slow to develop; a plug-in from Adobe currently supports many of its features, but it leaves some of the same integration problems as Flash. The next versions of both Firefox and Opera browsers will have built-in support for SVG, but that still leaves it as a niche technology that can be used only on internal projects.

SVG is also missing a canvas element, so there is no way for users to draw on elements, as can be done with Flash. To address this, a bitmap canvas was created by Apple for its Safari browser. This effort has since been codified by the Web Hypertext Application Technology Working Group (WHATWG). This group is supported by many browser developers, including Mozilla and Opera, so support will be forthcoming in new releases of these browsers; however, support by Internet Explorer seems less certain.

5.3.3 XML User Interface Languages

Many of the new technologies are missing widespread browser support, and XML-based user interface languages are no exception. These languages, which include Mozilla’s XML User Interface Language (XUL) and XAML, add the ability to describe normal application elements (such as menus, scrollbars, text boxes, and buttons) in an easy-to-use XML markup. Microsoft and Mozilla built their XML languages to allow for the creation of highly interactive rich applications that look and feel much like native applications right out of the box. However, because they are supported only by a single vendor, they do create problems of lock-in and tie you to a specific browser. This lock-in makes for a much less compelling solution than widely compatible solutions built on top of JavaScript and HTML.

XUL was created to define the user interface of Mozilla’s browser and has been available for a number of years. Recently, it has begun to gain momentum as Firefox has increased in popularity, but it will never be able to move beyond niche products until other browsers support the language. XAML was created by Microsoft as part of its .NET effort, and it is scheduled to be released as part of Windows Vista. It’s hard to know what its effect will be until it’s widely released and until we know how accessible it will be to Web developers.

The rise of popular new Web browsers has led to the creation of exciting new Web technologies. The biggest problem is that most haven’t made it beyond being implemented in a single browser. As support for these new technologies increases, they may become larger players, adding in the technology needed to increase interactivity beyond the level that AJAX and dynamic HTML (DHTML) can reach on their own.

5.4 Summary

To get the most out of AJAX, you need to identify and target the areas where it will have the most effect and then take steps to monitor that effect. AJAX can be used in most any Web site design, but it’s most effective when used to speed up searching and multistep processes. For solving simple problems, just picking appropriate areas to apply AJAX will give good results. However, as complexity increases, you’ll want to add instrumentation to your applications to get hard data on the changes AJAX is causing. Using this data, you can fine-tune your approach and start down the path to effective AJAX. The final step in using AJAX effectively comes from looking at the usability of the graphical interfaces you’re creating; we’ll cover this process in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.255.44