Ajax represents a powerful new way of developing web applications. It does away with the traditional model of breaking down web applications into multiple pages that must constantly be loaded and reloaded. Instead, Ajax supports the development of applications that seamlessly update page content, pulling data from the web server behind the scenes, without requiring any page reloads. The end result is a faster, more desktop-like end-user experience. This chapter provides an overview of Ajax and the different technologies that it uses to provide web developers with the tools needed to create a new generation of powerful, fast, and responsive applications. This chapter will also provide an overview of a number of different Ajax applications, offering examples of the kinds of things that Ajax is capable of performing.
Specifically, you will learn:
• About Ajax and the different technologies that it comprises
• How traditional web applications differ from Ajax applications
• How to create your first Ajax application
• About different examples of Ajax as used in various web applications
PROJECT PREVIEW: THE JOKE OF THE DAY APPLICATION
In this chapter and in each of the chapters that follow, you will learn how to create an Ajax game application. Learning application development by creating computer games is not only instructional but helps make learning fun. This chapter’s application. It begins by displaying a web page showing the opening punch line of a joke, as demonstrated in Figure 1.1.
As you can see, the application’s opening page consists of an HTML header and a button that when pressed uses Ajax to send a request to the web server. In response, a text file stored on the web server is returned to the browser, where its contents are then displayed in the browser, immediately under the application’s button control, as demonstrated in Figure 1.2.
Ajax, also known as Asynchronous JavaScript and XML, is a term used to refer to a collection of related web technologies. These technologies offer web developers the ability to create web applications that are able to dynamically interact with users and to work behind the scenes with web servers to retrieve application data. The data can then be displayed in the browser without requiring any page refreshes. The end result is the development of web applications that look and feel like desktop applications.
By 2005, many websites, most notably Google, were hard at work developing a whole new generation of applications (Google Maps, Google Suggest, etc.). Then on February 18, 2005 Jesse James Garrett wrote an article titled “Ajax: A New Approach to Web Applications,” coining the term Ajax for the very first time. From here, things really took off.
Ajax applications are faster and more responsive than traditional web-based applications. Improved performance is attained by modifying web applications so that they exchange smaller amounts of data with web servers. As a result, web servers no longer have to generate and return entire web pages in response to every user request or interaction with the application. Since only small amounts of data are exchanged in place of web pages, web page refreshes can be eliminated.
As this book will demonstrate, Ajax provides access to an enormously powerful set of development capabilities. However, just because you can use Ajax to perform all kinds of tasks does not mean that you should use it. Like all good things, Ajax is often best used in moderation. For example, if you need for the user to fill out and submit a form, you can do so without using Ajax. However, if you need to dynamically update a web page, then Ajax is the way to go.
With Ajax, data exchanged between web browsers and web servers is passed asynchronously behind the scenes. This means that Ajax applications can submit requests to the web server without having to pause application execution and can process the requested data whenever it is returned. Instead of submitting data to the web server using a form, Ajax applications submit requests using a special browser object known as the XMLHttpRequestobject. This object is the key component of Ajax that enables asynchronous communication.
Prior to Ajax, web developers had access to a collection of client-side web development technologies collectively referred to as DHTML. Using DHTML, web developers are able to dynamically update web pages using data collected from the user when interacting with the application.
DHTML is a collection of technologies, including HTML, CSS, JavaScript, and the DOM that when used together provide web page developers the ability to create dynamic web page effects like animation, graphical rollovers, and dynamic menus. It is strictly used to develop client-side automation and effects. Ajax embraces all of the same technologies as DHTML and adds the XMLHttpRequest object and XML into the mix.
Ajax is a collection of technologies all of which have been around for a number of years. Each of these technologies was developed for various reasons that had nothing to do with Ajax. However, because of their complementary nature, web developers have discovered that when used together, these technologies provide a robust and powerful environment for creating and running web applications. The individual technologies that make up Ajax include:
• JavaScript. The programming language used to develop Ajax applications, tying together the interaction of all of the other Ajax technologies.
• XML. Provides a means of exchanging structured data between the web server and client.
• The XMLHttpRequest object. Provides the ability to asynchronously exchange data between web browsers and a web server.
• HTML and CSS. Provides the ability to mark up and style the display of web page text.
• The Document Object Model or DOM. Provides the ability to dynamically interact with and alter the web page layout and content.
Traditional Web Development Versus Ajax Development
Until the last couple years, web applications have lagged well behind desktop applications in regard to their look and feel, made all the worse by performance problems brought on by slow internet connections. However, with the advent of Ajax, all this is beginning to change. Using Ajax, web developers can now create robust web-based applications capable of rivaling their desktop counterparts. When combined with today’s high-speed internet access and powerful web servers, Ajax applications are capable of offering a level of performance that makes web-based applications a viable option for today’s computer users.
Thanks to Ajax, web applications no longer have that web feel. For example, rather than forcing customers to move from one screen to another when making purchases, Ajax applications can seamlessly allow customers to select merchandise, add it to a shopping cart, and then complete the purchase all from the same web page, without once ever forcing a screen refresh or requiring the customer to advance through a series of screens.
Traditional web applications are made up of any number of loosely integrated web pages, which are then displayed in a predefined order through links embedded within HTML pages.
As such, in order to work with traditional web applications, the user must move from web page to web page interacting with a different portion of the application in a step-by-step process. Each time the customer clicks on a link to the next inventory page, a brief wait ensues while the customer waits for that page to be loaded.
Using this traditional approach, HTTP requests are submitted to the web server in response to user actions. Upon receiving the request, the web server satisfies the request by returning a new web page, which the web browser then displays. This interaction is depicted in Figure 1.3.
When processing the incoming request, the web server may perform any number of actions, including retrieving data from files, databases, or applications that run on the server. Once it has collected the data needed to satisfy the request, the web server may need to further process this data before generating the HTML page into which it will be embedded.
The data retrieved from the web server can be a plain text file stored on the web server or it may be data retrieved from a server-side database or generated after some processing has occurred on the web server. A number of different server-side programming languages are available. These languages include PHP, ASP, Ruby on Rails, and Java Servlets.
Consider a typical online merchant example. The merchant’s web application might require customers to review dozens of different pages in order to locate and select different items for purchase. Once the user has finished shopping and has selected all of the items she wants to purchase, a summary page is generally displayed requesting the customer to confirm the contents of her cart. From here, the application must then load a page that contains a form into which credit card information must be entered. Once submitted to the application’s web server for processing, the user must wait for a purchase confirmation page to be returned. After clicking on a button to provide confirmation and complete the transaction, the customer must wait for the web server again to complete the purchase, after which a final page, serving as a receipt, is displayed. At every step within the application, the customer must wait as the web server processes the user’s input and downloads new web pages for display. Using Ajax, you can change this application model so that only the absolute minimum amount of data needed to be exchanged is passed between the web browser and the server. This speeds things up a lot.
By passing data in place of web pages, and allowing data to be displayed within an existing web page, web application developers are able to give their applications a desktop-like feel. This replaces the loosely integrated web pages with a tightly integrated presentation. Ajax applications also help to better balance the use of resources. This is accomplished by adding an additional layer, referred to as the Ajax engine, into the mix as depicted in Figure 1.4.
Once the initial web interface page is loaded, communication between the web browser and web server can be performed by passing data in place of entire web pages. Because small amounts of data can now be passed asynchronously, network payload is decreased and things speed up. Asynchronous processing is accomplished through the execution of JavaScript function calls. Asynchronous processing also significantly cuts down on wait time by eliminating the need for page refreshes. In fact, while waiting for new data to be returned from the web server, the user is free to use other parts of the applications. Small amounts of data sent back by the web server may be sent as plain text. On the other hand, larger and more complicated collections of text are usually sent using XML.
In addition to plain text and XML, Ajax applications also support the exchange of data using JavaScript Object Notation or JSON. This book will show you how to work with both plain text and XML. Although its usage is not demonstrated, more information on JSON is provided in Chapter 7, “Working with XML.”
Asynchronous processing also reduces the web server’s workload, allowing more work to be done on the client computer when necessary. As the workload on the web server is reduced, the web server is able to respond more quickly and to handle an increased number of connections from other customers.
EXAMPLES OF REAL WORLD AJAX APPLICATIONS AND WEBSITES
Enough with all this talk about Ajax and what it is capable of doing. Let’s spend a few minutes looking at some examples of Ajax in action. Specifically, let’s look at a number of well known and not so well known websites and look at examples of how they have used Ajax to enhance their web applications. By the time you have completed this whirlwind tour, you should have a pretty good idea of the many different kinds of tasks that you can use Ajax to tackle.
One of the earliest adapters of Ajax was large search engines, which realized that Ajax could be used to greatly improve a search engine’s ability to provide users with a better experience. Using Ajax, search engine developers were able to go beyond just displaying a list of URLs and website descriptions and discovered that they could provide web surfers with all kinds of additional information, quickly retrieved behind the scenes based on visitor behavior.
A9.com
Amazon.com was one of the earliest websites to take advantage of Ajax. It used Ajax to help build its A9.com search engine (www.a9.com), as shown in Figure 1.5, which web surfers can use to search both the internet and amazon.com’s online catalog.
When used to perform a search, the results returned by A9.com look very much like those of any other search engine. Using Ajax, the developers of this search engine added a Site Info feature that displays additional information about a website when the user moves the mouse pointer over the link, as demonstrated in Figure 1.6. Everything works quite seamlessly, without any screen refreshes. Web surfers with high-speed internet access experience almost no wait time at all.
Ask.com
The developers of the Ask.com website’s search engine (www.ask.com) have used Ajax to enhance their search engine, allowing web surfers to preview websites as demonstrated in Figure 1.7 and to use this information when deciding whether to click on the site’s URL.
Only URL links that are preceded by graphical binoculars can be previewed. To preview the site, simply move the mouse pointer over the binoculars. The preview picture that is displayed is not collected in real time and therefore it may be a little out of date.
Another really neat use of Ajax is in the use of suggestion-based search engines, which retrieve data from the web server based on user keystrokes. There are many variations of this type of Ajax application.
Google was one of the first web companies to heavily invest in Ajax. It used Ajax in the development of a whole new generation of online applications including Google Gmail, Google Maps, and Google Suggest (http://www.google.com/webhp?complete=1&hl=en), which is pictured in Figure 1.8.
To use Google Suggest, all you have to do is begin typing. As you type, the application passes your keystrokes behind the scenes to one of Google’s servers and retrieves a list of topics that match what you have typed so far. As you continue to type, Goggle Suggest continues to update the list of topics that is displayed. You can either enter your own unique search term or select one of the entries that is displayed to initiate an internet search.
Amazon Zuggest
An interesting variation of Suggest is Amazon Zuggest (http://www.francisshanahan.com/zuggest.aspx), as demonstrated in Figure 1.9. This application monitors user keystrokes, retrieving and displaying items from amazon.com’s catalog that match up against whatever you enter. The more you type, the better the application is able to hone in on what you are looking for.
Online Ajax Dictionaries
Another great use of suggestion-based searching is in the development of dictionary and thesaurus type applications. One such application is ObjectGraph (http://www.objectgraph.com/dictionary/), as demonstrated in Figure 1.10.
Google Maps
One of Google’s best known and most popular applications is Google Maps (maps.google.com). As shown in Figure 1.11, Google maps provide a global view of the Earth, allowing visitors to view detailed pictures of any individual spot on the globe. Using Ajax, Google maps allows you to click on and drag the map to reveal different locations. Based on user input, new map images are returned from the server and displayed in the map portions of the applications, with near instantaneous results and no page refreshes.
Another website that has made notable use of Ajax is Netflix (www.netflix.com). Netflix is an online DVD rental service with over 6 million subscribers. Customers can search for and order movies, which are then either downloaded to the customer’s computer or mailed to their residence. As Figure 1.12 demonstrates, the Netflix website uses Ajax to display additional information about movies in a popup when the customers move the mouse pointer over its title.
Among the newest generation of applications now available on the internet are applications that let you run a virtualized computer operating system within your web browser. One example of such an application is ajaxWindows (www.ajaxwindows.com), as shown in Figure 1.13.
Figure 1.14 shows an example of ajaxWindows in action. As you can see, its overall appearance resembles that of a Windows operating system. Included as part of the operating systems are a number of common desktop applications, including a word processor called ajaxWrite and a paint program named ajaxSketch.
ajaxWrite and ajaxSketch are just two of a number of applications supplied as part of ajaxWindows. In addition to accessing these applications through the ajaxWindows application, you can also access and run them directly within your browser. For example, by visiting http://us.ajax13.com/en/ajaxwrite/ you can launch ajaxWrite. As demonstrated in Figure 1.15, ajaxWrite very much resembles Microsoft Word. It can be used to create, edit, write, and print text documents. It can even save documents in Microsoft Word format, which can be stored online or saved directly to your computer’s hard drive.
Another prominent web application built in part using Ajax is Flickr (www.flickr.com). Flickr is an online photo management tool that is capable of rivaling most desktop photo management programs. As demonstrated in Figure 1.16, Flickr lets you upload and manage all your personal photos.
Flickr provides users with access to an application called Organizr. Using this application, Flickr users can organize and manage their uploaded photos. Organizr allows users to drag and drop photos and to create and modify photo descriptions and groupings. Organizr looks and feels like a desktop-based photo management program.
Ajax Instant Message Applications
Another category or application that Ajax is commonly used to develop is instant messaging. One such instant message application is ajax im (www.ajaxim.net). As shown in Figure 1.17, ajax im (asynchronous JavaScript and xml instant messenger) is a browser-based IM client that allows users to send and receive text messages to one another without ever refreshing the browser window.
Another interesting category of applications that Ajax has been used to create is online calendar and time management applications. One such application is calendar hub (www.calendarhub.com), as shown in Figure 1.18. CalendarHub lets you view calendar data using a day, week, month, and list views. You can post as many calendar entries and to-dos as you want. You can even share your calendar with others and receive notifications via email.
Using Ajax, CalendarHub supports a drag and drop interface that allows you to move calendar entries around and add new entries to the calendar without any page refreshes.
BACK TO THE JOKE OF THE DAY APPLICATION
It is now time to turn your attention to the development of this chapter’s Ajax project, the Joke of the Day application. This application, when loaded into the web browser, will present the user with a web page that displays the opening line for a joke. Underneath the joke is a button that, when pressed, instructs the application to retrieve the joke’s punch line using Ajax, which is stored in a plain text file on the application’s web server.
Since this book has yet to introduce you to the intricacies of Ajax development, such as JavaScript or how to work with the XMLHttpRequest object, don’t worry if you do not fully grasp what each individual code statement in the application is doing. As long as you can understand the HTML portions of the examples, you should be in good shape. For now, try to keep your focus on the overall process of converting a traditional web application into an Ajax application. Everything will become clear as you make your way through this book, and by the time you are done, simple applications like the Joke of the Day application will seem quite elementary to you.
To help keep things simple, the development of this application will be performed in five steps, as outlined here:
2. Create the application’s text file.
3. Test the HTML version of the application.
4. Enhance the application using Ajax.
5. Execute your new Ajax application.
The first three steps will demonstrate how to create and execute the application using HTML by following the traditional web development approach, and the last two steps will show you how to modify the application using Ajax. Although this initial application is relatively simple, it will walk you through the basic development steps required to update any typical web page using Ajax. As long as you follow along carefully with the instructions provided in each step, you’ll have your own copy of this application up and running in no time.
In order to follow along with this example you need access to a web server where you can upload your web pages. If you do not have a website, now would be a good time to sign up with a web host and get started. To find a web host, visit www.google.com and perform a search on “web host.” You will find plenty of web host providers ready and willing to help you get started. If you already have access to a website to which you can upload your web pages, I suggest that you begin by creating a subfolder in your web directory and that you do all of your Ajax work in it as you work your way through this book. This way, you won’t mess up anything on your website while learning and experimenting with Ajax.
Step 1: Writing the Application’s HTML
The first step in creating the Joke of the Day application is to create an HTML version of the application. To do so, open your preferred code or text editor—Microsoft Notepad or any text editor that can save plain text files will do—and create and save a new file named index.html. Once this has been completed, you need to add the application’s HTML statements, which are shown next, to the file.
<HTML>
<HEAD>
<TITLE>HTML Joke of the Day</TITLE>
</HEAD>
<BODY>
<H1>Where do bees go when they get married?</H1>
<A href="joke.txt">Fetch Answer</A>
</BODY>
</HTML>
As you can see, this version of the Joke of the Day application is a typical HTML page, consisting of head and body tags. The head section includes a title tag that displays the name of the application and the body section contains a level 1 heading that displays the application’s joke, followed by a link to another file named joke.txt where the joke’s punch line is stored. The joke.txt file is a plain text file made up of a single line of text. When clicked, the link opens and then displays the contents of the file in the web browser.
If you want, you could modify this example to open another HTML page that displays the punch line instead of a text file.
Step 2: Creating the Application’s Text File
Now that you have the index.html page created, it is time to create the joke.txt file. Do so by opening your preferred text file editor and typing the sentence shown in Figure 1.19 into it.
As you can see, this file consists of a handful of words, saved as a plain text file. Once you have keyed in the file’s text, save the file in the same place that you saved the index.html file.
Step 3: Uploading and Testing the HTML Version of the Application
Once you have created both the index.html and joke.txt files, you need to upload them to your web server for testing. You may be able to perform this step using FTP or using a web-based administrative interface provided by your web host provider. Consult with your web host to see which of these options are available to you.
Once you have uploaded these two files to your web server, you should be ready to test this temporary HTML version of the Joke of the Day application. To do so, open your web browser and type the URL for the index.html web page. The URL that you use will vary based on the name of your website’s URL and the location on that web server where you uploaded the application’s files. For example, the following URL would be used to load the application into your web browser if your website’s URL was www.tech-publishing.com and you elected to create a subfolder named “test” into which you placed the application’s files.
http://www.tech-publishing.com/test/index.html
Actually, since all you are working with at this point is HTML, you can test your application directly from your desktop without first uploading its HTML files to your web server. To do this, all you have to do is start up your web browser and instead of loading index.html by specifying its URL, you click on the File menu and select the Open command and then specify the name and location of the HTML file. To work, a copy of the joke.txt file must reside in the same folder as the index.html file.
Once loaded into your web browser, you should see the web page shown in Figure 1.20 appear, displaying the application’s joke and a link labeled Fetch Answer.
To view the joke’s punch line, click on the link. Within a few moments, the browser window will blink and the contents of the joke.txt will load, as shown in Figure 1.21. As you can see, this is a pretty standard HTML application. It involves loading an initial web page, after which additional data is presented by loading new web pages into the browser window while the user waits for the browser’s window to reload.
Since this application was small and does not make use of large amounts of graphics or sounds, everything happens pretty quickly, so you may not notice a significant delay. However, if the web page was loaded down, the delay would have been more obvious.
Step 4: Turning the HTML Application into an Ajax Application
Now that you have the HTML version of the Joke of the Day application up and running, you are ready to convert it to an Ajax application. Do so by opening the index.html application in your preferred code or text editor and modifying it as shown here:
Beginning new Ajax applications by first developing them as HTML applications is a very popular approach to Ajax development. Applying Ajax to an existing HTML page is often easier than trying to develop a new Ajax application from scratch. In addition, since Ajax does have a number of limitations that have yet to be completely overcome, as discussed in Chapter 10, “Important Ajax Design Issues,” having an HTML and an Ajax version of your application provides the ability to service web surfers whose computers can and cannot support Ajax applications. You will learn more about dealing with this type of situation in Chapter 3, “A Deeper Dive into JavaScript.”
<HTML>
<HEAD>
<TITLE>Ajax Joke of the Day Application</TITLE>
<SCRIPT language = "javascript" type = "text/javascript">
var Request = false;
if (window.XMLHttpRequest) {
Request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request = new ActiveXObject("Microsoft.XMLHTTP");
}
function retrieveJoke(url, elementID) {
if(Request) {
var RequestObj = document.getElementById(elementID);
Request.open("GET", url);
Request.onreadystatechange = function()
{
if (Request.readyState == 4 && Request.status == 200) {
RequestObj.innerHTML = Request.responseText;
}
}
Request.send(null);
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Where do bees go when they get married?</H1>
<FORM>
<INPUT type = "button" value = "Fetch Answer"
onclick = "retrieveJoke(’joke.txt’, ’DivTarget’)">
</FORM>
<DIV id="DivTarget"> </DIV>
</BODY>
</HTML>
As you can see, the Ajax version of the Joke of the Day application involves the addition of a considerable number of new statements. Since this book has yet to review the intricacies of creating Ajax applications, this chapter won’t go into great detail about what each and every one of the new statements in index.html does. Instead, let’s keep things at a reasonably high level. Figure 1.22 breaks down the new code statements that you have added to the Ajax version of the application.
As Figure 1.22 shows, most of the new statements that have been added to index.html make up a JavaScript, which begins and ends with <script> and </script> tags. Within the script, variables are used to store data, an XMLHttpRequest object is set up to enable communication with the application’s web server, and a function is used to set up a connection to the web server and retrieve a text string containing the joke’s punch line.
The rest of the statements added to index.html are used to create a form made up of a button that, when clicked, triggers an event that results in the execution of a function named retrieveJoke(). There is also a pair of Div tags in the body section that provide the application with a placeholder where the joke’s punch line will be displayed.
Hopefully, you already know how to work with forms and Div tags. Just in case, this book will briefly touch on them as well as introduce you to programming with JavaScript and the XMLHttpRequest object in Chapters 3 and 4.
Step 5: Executing Your New Ajax Application
Once you have created the Ajax version of the Joke of the Day application, you will need to upload it to your website before you can test its execution. Once you have done this, open your web browser and enter the URL for the index.html web page. For example, the following URL would be used to load your Ajax application if your website’s URL was www.yourURL.comand you elected to create a subfolder named “test” into which you placed the application’s files.
http://www.yourURL.com/test/index.html
Once loaded, your copy of the Joke of the Day application should operate exactly as was demonstrated at the beginning of this chapter, instantly displaying the joke’s punch line when the Fetch Answer button is pressed, without any page refresh.
All right, at this point your new Ajax version of the Joke of the Day application should be ready for testing. To test the application, you had to upload the modified version of the HTML page to your web server and then load it using your web browser. Once loaded, you were able to view the application’s new interface and click on its button control in order to retrieve and load the punch line for the application’s joke. Assuming that you followed along carefully when creating this new application and that you did not run into any problems uploading it to your web server, everything should work as described.
In the event that you run into any errors, make sure you have entered the correct URL for the application into your browser. If your URL is okay, go back and double-check the statements that make up the Ajax version of the application and look for any mistakes that you may have made when keying it in.
You will find a copy of this application’s source code files on the book’s companion website, located at http://www.courseptr.com/downloads
This chapter provided an introduction to Ajax. You learned how to use the different technologies that Ajax harnesses in order to build fast and responsive desktop-like applications. You learned how Ajax applications differ from traditional HTML applications and reviewed a number of different websites where Ajax has been used, examining how Ajax was used to enhance and improve the application. You also learned how to create your first Ajax application, which you created by modifying an existing HTML application to communicate with and retrieve a text file from a remote web server.
Before you move on to Chapter 2, “An Introduction to JavaScript,” consider setting aside a little extra time to improve the Joke of the Day application by addressing the following challenges.
CHALLENGES |
1. The joke told by the Joke of the Day application is somewhat bland. Why not spice it up a bit by replacing it with a joke that reflects your own sense of humor? |
2. Consider creating a copy of the Joke of the Day application, perhaps making a Joke of the Week application, and set it up to tell a different joke. |