Previous Page
Next Page

Refreshing Server Data

Our Ajax application has fetched information from the server and then parsed the data and acted upon it. Now we'll show you how to make the application retrieve a new version of the data from the server, which automatically refreshes the page. Script 15.7 contains the necessary JavaScript.

Script 15.7. Use this script to automatically refresh server information.

window.onload = initAll;

var xhr = false;
function initAll() {
     if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
     }
     else {
        if (window.ActiveXObject) {
           try {
              xhr = new ActiveXObject ("Microsoft.XMLHTTP");
           }
           catch (e) { }
        }
     }

     if (xhr) {
        getPix();
     }
     else {
        alert("Sorry, but I couldn't create an XMLHttpRequest");
     }
}

function getPix() {
     xhr.open("GET", "flickrfeed.xml", true);
     xhr.onreadystatechange = showPictures;
     xhr.send(null);

     setTimeout("getPix()",5 * 1000);
}

function showPictures() {
     var tempDiv = document.createElement ("div");
     var tempDiv2 = document.createElement ("div");

     if (xhr.readyState == 4) {
        if (xhr.status == 200) {
           tempDiv.innerHTML = xhr.responseText;
           var allLinks = tempDiv. getElementsByTagName("a");

           for (var i=1; i<allLinks.length; i+=2) {
              tempDiv2.appendChild(allLinks[i]. cloneNode(true));
           }

           allLinks = tempDiv2. getElementsByTagName("a");
           var randomImg = Math.floor (Math.random() * allLinks.length);
           document.getElementById ("pictureBar").innerHTML = allLinks[randomImg].innerHTML;
        }
        else {
           alert("There was a problem with the request " + xhr.status);
        }
     }
}

To refresh server information:

1.
function getPix() {
  xhr.open("GET", "flickrfeed.xml", true);
  xhr.onreadystatechange = showPictures;
  xhr.send(null);

  setTimeout("getPix()",5 * 1000);
}



Where the previous script did the xhr call inside initAll(), this script pushes it down into its own function, getPix(). There's one addition: the setTimeout() afterwards. Five seconds after the script has grabbed a random image, it goes and gets another.

2.
for (var i=1; i<allLinks.length; i+=2) {
  tempDiv2.appendChild(allLinks[i]. cloneNode(true));
}



This is almost the same loop that's in the previous task, with one difference: instead of appending the nodes to the Web page, it adds them to another temporary div.

3.
allLinks = tempDiv2. getElementsByTagName("a");
var randomImg = Math.floor (Math.random() * allLinks.length);
document.getElementById ("pictureBar").innerHTML = allLinks[randomImg].innerHTML;



When the loop completes, we want to figure out one random image out of all of them to display. We start by creating another array of links (now with just the linked photographs instead of all the links). We then calculate a random number between zero and one less than the number of images, using Math.random() and Math.floor() as we did back in Chapter 4 in "Displaying a Random Image." And finally, we use that random number as an index into the allLinks array to grab the one image, and we put that into our Web page (Figure 15.4).

Figure 15.4. The script fetches one image after another.


Tips

  • You might wonder why this script bothers to read from the same XML file every timeafter all, if the file isn't changing, why not just keep the data in variables after the first time through? If you keep in mind the technique referred to in the previous sidebar ("Getting Your Data"), you'll then realize that the XML file could be changing at any point. Say your server-side program grabs a new version of the XML file every few minuteswhy should anyone have to wait to see the latest pictures? This way, your site's visitors always get the latest possible version.

  • If you take the approach just mentioned, you're likely to run into the Ajax drawback covered earlier in this chapter: caching. Different browsers (and different versions, and different platforms) all have their own unique caching peculiarities, most of which are solved by modifying the headers as discussed earlier. Another solution many recommend is to change the GET to a POST. But here's what we've found that works: swap the order of the open() and onreadystatechange, as shown above in step 1.



Previous Page
Next Page