Click here to Skip to main content
15,741,011 members
Articles / Web Development / HTML
Posted 31 Mar 2010


15 bookmarked

Slideshow using Asynchronous JavaScript and XML, a.k.a. Ajax

Rate me:
Please Sign up or sign in to vote.
4.38/5 (8 votes)
4 Apr 2010CPOL4 min read
This is a simple Slideshow client web application using Asynchronous JavaScript and XML.


This is a simple SlideshowClient web application having next/previous manual image switching and normal Start/Stop slideshow options.This application basically uses client side scripting using JavaScript and XMLHTTPRequest.

Using the Code

Our ultimate aim is to show the images and switch them without posting the page back. So definitely we should use any client side scripting language for this asynchronous behavior and of course JavaScript to do the job.

If we are only using images, then we can directly change image control source within the JavaScript. But here we want some description or some display information for each image. So I choose a simple XML file to store the data required for the slideshow. I only added description here as informational data but we can add more details as per the requirement.

<?xml version="1.0" encoding="utf-8" ?>
    <Description>Colors of Life</Description>
    <Description>Leaf on the Floor</Description>
 ///More Slideshow elements here

In the web page, I added some HTML controls required for the slideshow. So now comes the question. How does it actually work? It's not much complicated. I am using the hero XMLHttpRequest for getting the data from the server each time user interacts with the application. Actually what does this XMLHttpRequest do? By using XMLHttpRequest, we can send request to server and get data back in the script without reloading the entire page. So it's very popular in web development especially in AJAX. Before sending the request to the server, we should use open method for specifying the parameters needed for the request object.

JavaScript"GET", "/Data/SlideshowClientData.xml", false);

In the above method, the first parameter indicates the HTTPRequest method to use with the request object, the second parameter indicates the URL or path of the request and the third parameter is a boolean indicating whether the request is synchronous or not. If it's asynchronous, then the calling method in the script will not wait for the request to complete and we need to use the onreadystatechange event to listen for the completion of the request. If the request is completed, then xmlHttpRequest.readyState value will be 4. If it's synchronous then the method will wait until the request is completed and then it'll continue the execution. Here, I am using false that means it's synchronous. After calling open method, we can use send method of the request object which will send the request to the server. We can pass parameters in the send method if we use post method. So after completing the request, we'll get the response either as XML using xmlHttpRequest.responseXML or as plain text using xmlHttpRequest.responseText. I took the advantage of the XML response and later iterating the nodes to find the image selected.So our request processing looks like:

//cross browser object for XMLHttpRequest
var xmlHttpRequest = (window.XMLHttpRequest) ? 
	new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');"GET", "/Data/SlideshowClientData.xml", false);
//fetching the responseXML from the request
xmlDoc = xmlHttpRequest.responseXML; 

I added onload attribute to the body element in my aspx page for creating the XMLHttpRequest object and also getting the response and keeping it in our script variables:

<body onload="LoadData();">

So we got an XML response from responseXML attribute of the request object. So how are we going to parse this XML data? For parsing the XML data, we use element.selectSingleNode("ElementName") showing Next/Previous image and its description. I have currentSlideshowId variable in script which is initially set to 1199. I use Ids from XML data to identify the selected images which are starting from 1200 in the XML. When a user clicks Next/Previous image, I add/subtract currentSlideshowId value by 1. So I iterate through xmlDoc.documentElement.childNodes, checking with the currentSlideshowId and setting the selected image and its description.

function ShowNextImage() {
    if (xmlDoc != null) {
        var flag = false;
        //Getting Previous image from data XML
        for (var i = 0; i < xmlDoc.documentElement.childNodes.length; i++) {
            var element = xmlDoc.documentElement.childNodes[i];
            if (element.nodeType == 1 && 
		element.selectSingleNode("SlideshowId") != null &&
                 	element.selectSingleNode("SlideshowId").nodeTypedValue == 
		currentSlideshowId + 1) {
                document.getElementById('slideshowimg').src = 
                document.getElementById('description').innerHTML = 
                currentSlideshowId = currentSlideshowId + 1;
                flag = true;

        if (!flag && interval != null && anchor != null) {

But when I checked this behavior in different browsers, I found that element.selectSingleNode("SlideshowId") is not supported in some browsers. So I tried for some workarounds and finally found Wrox's article XPath support in Firefox. I added selectSingleNode prototype for Element and used XPathEvaluator to find the selected child node for the element and it worked as expected. We are giving an xPath as input param for the prototype and finding the specified node using XPathEvaluator.evaluate method, XPathResult.FIRST_ORDERED_NODE_TYPE returns the first node matches the given xPath.

var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(xPath, this, null, 
		XPathResult.FIRST_ORDERED_NODE_TYPE, null); 

Also I created attribute result.singleNodeValue.nodeTypedValue which doesn't exist for non Internet Explorer browsers. So now nodeTypedValue returns the selected node value for both Internet Explorer and other browsers.

 function ElementProtoType() {
    if (document.implementation.hasFeature("XPath", "3.0")) {
        //Some of the browsers not supporting selectSingleNode
        Element.prototype.selectSingleNode = function(xPath) {
            var evaluator = new XPathEvaluator();
            var result = evaluator.evaluate(xPath, this, null, 
			XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            if (result != null && result.singleNodeValue != null) {
                result.singleNodeValue.nodeTypedValue = 
                return result.singleNodeValue;
            else {
                return null;

One more functionality is Automatic playback or in other words, the real slideshow. How we are going to do that? Of course, by using setInterval method in JavaScript. This method will call a method at a regular interval of time until clearInterval() is called.

interval = setInterval("ShowNextImage()", 2000); 

This will fire the ShowNextImage() method at 2 sec intervals. If a user stops the slideshow, we are clearing this handler by using the interval Id returned by the setInterval method:

if(interval != null) {
    interval = null;

I tested this application in almost all latest browsers including Internet Explorer, Firefox, Google Chrome, Safari and it is working good.

Points of Interest

If we use larger size images, adjust the timer according to the loading time for image, otherwise in some browsers while playing the slideshow, it won't get time to load the image and it'll only slide through the description.


  • Created on : 31.03.10


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer Tata Consultancy Services
India India
I have been working in different .NET Technologies like ASP.NET,WPF,Silverlight for the last few years.I am enjoying my life as a Programmer and spending time with my Family,Friends & Camera.

My Technical Blog

My Photo Blog

Comments and Discussions

GeneralMy vote of 5 Pin
Member 767875812-Oct-11 3:00
Member 767875812-Oct-11 3:00 
GeneralMy vote of 3 Pin
kumarvinit867-Mar-11 1:44
kumarvinit867-Mar-11 1:44 
It is a good example of changing images by xml
GeneralMy vote of 1 Pin
R. Giskard Reventlov1-Apr-10 0:02
R. Giskard Reventlov1-Apr-10 0:02 
GeneralRe: My vote of 1 Pin
Arun Jacob4-Apr-10 21:12
Arun Jacob4-Apr-10 21:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.