Monday, April 24, 2006

Rich Ajax slide shows with DHTML and XML

18 Apr 2006

Learn to create an Asynchronous JavaScript and XML (Ajax) client-side slide show that's animated using "Ken Burns Effects." Here, you discover how to build XML data sources for Ajax, request XML data from the client, and then dynamically create and animate HTML elements with that XML.

If the Web 2.0 revolution has one buzzword, it's Asynchronous JavaScript and XML (Ajax). The client-side interactivity in applications such as Google Maps™ mapping service and Gmail™ webmail service make Ajax both exciting and useful. The technologies of Ajax, including Hypertext Markup Language (HTML), JavaScript coding, Cascading Style Sheets (CSS), XML, and asynchronous Web requests, can create far more compelling Web interactions than those we saw in Web V1.0. Of course, these technologies have been around since Microsoft® Internet Explorer® V4, but only recently have other high-profile applications displayed the benefits.

How difficult is Ajax to implement? Each element of the Ajax model is relatively easy to learn. But the trick is blending all the elements into a seamless experience. Often that problem is compounded, because different individuals do the client-side and server-side coding. This article shows how just one person can write a small Ajax-based slide viewing application in a couple of hours.

Slide shows with Ajax

Personal image-management applications such as Apple® iPhoto® on the Macintosh® have popularized the slide show view. In a slide show, the images appear in a timed sequence, with images fading in and out. In addition, the images are moved and zoomed in what has become known as the "Ken Burns Effect."

In this example, I have the browser download a list of images from the server. Then, I use that list of images to compose a slide show using Dynamic HTML (DHTML). I animate the images with random slow moves, zooms, and fades to give a pleasing version of the Ken Burns Effect without having to download Macromedia® Flash or any other heavyweight animation tools.



Back to top


Architecture

To understand what's different about Ajax, you must first understand the current model of Web programming. The simple interaction between client and server is shown in Figure 1.


Figure 1. The Web V1.0 model of client-server interaction
Web V1.0 client-server interaction

The Web browser, or client, makes a GET or POST request of the Web server. The server formats an HTML response. The client parses the HTML and displays it to the user. If the user clicks another link or button, another request is made to the server, and the current page is replaced with the new page that the server returns.

The new model is more asynchronous, as shown in Figure 2.


Figure 2. The Ajax model of client-server interaction
Ajax client-server interaction

In this new model, the server returns an HTML page, just as before. But now this page has some JavaScript code on it. That code calls back to the server for more information as needed. Those requests can be made as simple GET requests for Representational State Transfer (REST) service, or as the POST requests required for SOAP.

The JavaScript code then parses the response, often encoded as XML, and updates the HTML on the page dynamically to reflect the new data. In addition to XML, engineers are returning data encoded in the JavaScript Serialized Object Notation (JSON) format. This data is easier for a browser to understand but not for other client types. The value of returning XML is that clients other than browsers can interpret the data. The choice is up to you and depends on the application.



Back to top


Serving the image information

The first step in developing the Ajax slide show is to put together the REST data service. In this example, I use a PHP page that returns all the available slide show images and their sizes (width and height). All the images reside in a directory named images. The names of the files are name_width_height.jpg -- for example, oso1_768_700.jpg, which means that the file is a picture of Oso, one of my dogs, and is 768 pixels in width and 700 pixels in height. I use this kind of naming all the time, because it makes it easy to see what the width and height of an image are without cracking open Adobe® PhotoShop® or Macromedia Fireworks.

To serve up the list, I use the PHP server code shown in Listing 1.


Listing 1. The slides.php server page





"
width=""
height="" />



The code is relatively simple. To start, it sets the content type to XML. It's critical to get the browser to recognize the document as XML and to create a document object model (DOM) for it. The code starts the tag, and then reads the images directory to create a tag for each image it sees. Finally, the script closes the tag.

If you navigate the Mozilla® Firefox® browser to the page, hosted (in my case) on my localhost in a directory called kenburns, you see the result shown in Figure 3.


Figure 3. The output of the slides.php server script
Slides.php server script output

There are three images: one of my daughter and two of my dogs. Obviously, you can add whatever detail and multimedia you want here, but I've tried to keep it simple for this example.



Back to top


Retrieving the XML

The next step is to write an HTML page (shown in Listing 2) that will read the data from the service and verify that the Ajax connection between the browser and the server works. This HTML code, with embedded JavaScript code, retrieves the XML and brings up an alert shown in the text that the server returns.


Listing 2. A simple Ajax fetch page









The code grabs the XML content from a specified URL, then the loadXMLDoc function starts the Ajax request. That request goes off asynchronously to retrieve the page and return the result. When the request is complete, the processReqChange function is called with the result. In this case, the processReqChange function displays the value of the responseText function in an alert window. The result of firing up this page in my Firefox browser is shown in Figure 4.


Figure 4. The XML shown in an alert window
XML in alert window

That's a good start. I'm definitely getting the XML data back from the server. But let me point out a few things. First, notice that the URL is an absolute path, domain name and all. That's the only valid URL style for Ajax. The server code that writes the Ajax JavaScript code always creates valid, fully formed URLs.

Another thing that isn't evident here is the Ajax security precautions. The JavaScript code can't ask for just any URL. The URL must have the same domain name as the page. In this case, that's localhost. But it's important to note that you can't render HTML from www.mycompany.com, and then have the script retrieve data from data.mycompany.com. Both domains must match exactly, including the sub-domains.

Another item of interest is the code in loadXMLDoc, which seems to do back flips to create a request object. Why so much hassle? Pre-version 7 Internet Explorer doesn't have the XMLHTTPRequest object type built in. So, I must use Microsoft ActiveX® controls.

Finally, in the processReqChange function, you see that I look for readyState to be equal to 4 and status to be set to 200. The readyState value of 4 means that the transaction is complete. The status value of 200 means that the page is valid. You might also get error message 404 if a page isn't found, just like you see in the browser. I don't handle exception cases here, because it's just example code, but the Ajax code you ship should handle requests that return errors.



Back to top


Creating HTML dynamically

Before I show you how to create the slide show, I will extend the current example by having the processReqChange function create an HTML table with the results of the XML request from the server. In that way, I can test two things: that I can read the XML and that I can create HTML from it dynamically.

Listing 3 shows the updated code that creates a table from the returned XML.


Listing 3. The enhanced test page
























It's tough to show what this looks like in a browser without a movie. So, I took a single snapshot of the show and present it in Figure 6.


Figure 6. A snapshot from the slide show
Snapshot

This page starts by bringing in the base classes through the src items on the










function processReqChange()
{
if (req.readyState == 4 && req.status == 200
&& req.responseXML != null)
{
var items = [];
var nl = req.responseXML.getElementsByTagName( 'slide' );
for( var i = 0; i < nli =" nl.item(" src =" nli.getAttribute(" width =" parseInt(" height =" parseInt(" req =" false;" req =" new" req =" false;" req =" new" req =" new" req =" false;" onreadystatechange =" processReqChange;">




I moved the start_slides and load_slides functions into an external JavaScript file called SlidesShow.js to keep the length of this file short. The rest of the code is similar to what I had in the Ajax test page in Listing 2. But rather than insert an alert window or add items to a table, this code creates an array of slide information, and then calls load_slides and start_slides.

And that's it! An Ajax slide show using the Ken Burns Effect to move, zoom, and fade images dynamically.



Back to top


Adapting Ajax slide shows to your needs

In this article, I used object-oriented JavaScript code whenever possible. JavaScript is a fully object-oriented language, and although it might not use the class and interface keywords, it keeps your code clean and maintainable. I also recommend using Ajax frameworks if you can. I didn't use one here because I wanted to show a lightweight Ajax solution. But today's frameworks -- and there are many of them -- make it easier to write more portable Ajax and DHTML code.

In addition to what you've seen in this article, I have the following recommendations for your Ajax slide shows:

It used to be that you needed Flash or a similar application to make dynamic slide shows like the one in this article. With modern browsers, which include excellent support for DHTML with rich effects like opacity (or even rotation, blur, and so on, in Internet Explorer) and Ajax, you can do amazing things right in the browser. That means that your customers don't have to download fancy extensions or run potentially unsafe applications. They can just surf to your pages and get stunning graphic effects that will keep them coming back for more.




Back to top


Download

DescriptionNameSizeDownload method
Code and file samples for this articlex-ajaxslideshow/kenburns.zip705KBHTTP
Information about download methodsGet Adobe® Reader®


Back to top


Resources

Learn

Get products and technologies

Discuss


Back to top


About the author


Jack D. Herrington is a senior software engineer with more than 20 years of experience. He's the author of three books: Code Generation in Action, Podcasting Hacks, and the soon to be released PHP Hacks. He's also written more than 30 articles. You can reach Jack at jack_d_herrington@codegeneration.net.



source:http://www-128.ibm.com/developerworks/xml/library/x-ajaxslideshow/?ca=dgr-lnxw01AjaxSlid


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?