Parsing Server Data

Now that we have data from the server, we need to find the exact information we need and make sure that it is in a format that our Ajax application can use. To do that, we’ll first need to examine the information. Because the data is a nicely structured XML document, our script walks the XML document tree to find and extract the particular data we need and store it in variables. Then, if needed, the script can reformat the data for later use.

The HTML and CSS that are in Scripts 13.5 and 13.6 couldn’t be much simpler, so we’re only going to look at the code in the JavaScript file, Script 13.7. For this task, the XML file is data about photographs stored on Flickr; a portion of the XML can be seen in Script 13.8.

To parse information from the server:

1.
xhr.onreadystatechange = showPictures;
xhr.open("GET", "flickrfeed.xml", true);



Every time readyState changes, we want to call the showPictures() function. The file name we want to read off the server is flickrfeed.xml. Both those values are set here.

2.
var tempDiv = document.createElement("div");
var tempText = document.createElement("div");



Down in showPictures() is where the real work is done. We start by creating variables to store two elements: tempDiv and tempText, both of which are temporary div placeholders.

Script 13.5. This simple HTML page will be much more impressive with the addition of some JavaScript.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>My Second Ajax Script</title>
     <link type="text/css" rel="stylesheet" href="script02.css" />
     <script type="text/javascript" src="script02.js"></script>
</head>
<body>
     <div id="pictureBar"> </div>
</body>
</html>

Script 13.6. Only a little bit of CSS, but it’s needed to make the page look good.
img {
    border-width: 0;
    margin: 5px;
}

3.
var allImages = xhr.responseXML.getElementsByTagName("content");



The response back from the server contained XML, so we’re taking that response and looking for every content node. If you take a look at the XML in Script 13.8, you’ll see that there’s a lot of stuff there that we don’t care about at all—in fact, all we want is what’s in the <a> tags (and really, only half of those). Here, we’ve started to narrow down to just what we want.

4.
for (var i=0; i<allImages.length; i++) {



Now we need to loop through all the nodes that we found to get the actual data we want.

5.
tempText.innerHTML = allImages[i].textContent;
tempDiv = tempText.getElementsByTagName("p");



Because we’ve got XML data, we can use its textContent property to get the text of the node. Given that, we want to find all the paragraphs inside it—and there should be two of them.



Script 13.7. The additional JavaScript in this script allows you to parse the data you previously requested.
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) {
        xhr.onreadystatechange = showPictures;
							xhr.open("GET", "flickrfeed.xml", true);
        xhr.send(null);
     }
     else {
        alert("Sorry, but I couldn't create an XMLHttpRequest");
     }
}

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

     if (xhr.readyState == 4) {
        if (xhr.status == 200) {
           var allImages = xhr.responseXML.getElementsByTagName("content");
							for (var i=0; i<allImages.length; i++) {
							tempText.innerHTML = allImages[i].textContent;
							tempDiv = tempText.getElementsByTagName("p");
							var theText = tempDiv[1].innerHTML;
							theText = theText.replace(/240/g,"75");
							theText = theText.replace(/180/g,"75");
							theText = theText.replace(/_m/g,"_s");
							document.getElementById("pictureBar").innerHTML += theText;
           }
        }
        else {
           alert("There was a problem with the request " + xhr.status);
        }
     }
}



Script 13.8. This is an edited and shortened version of the XML file that Flickr provides; the original was approximately 500 lines long!
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xmlns="http://www.w3.org/2005/Atom"
        xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:flickr="urn:flickr:" xmlns:media="http://search.yahoo.com/mrss/">

     <title>Content from Paradise Ridge Sculpture Grove</title>
     <link rel="self" href="http://api.flickr.com/services/feeds/photoset.gne?set=72157600976524175&amp;nsid=23922109@N00&amp;lang=en-us" />
     <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dorismith/sets/72157600976524175"/>
     <id>tag:flickr.com,2005:http://www.flickr.com/photos/23922109@N00/sets/72157600976524175</id>
     <icon>http://farm2.static.flickr.com/1335/882568164_72eee9b41f_s.jpg</icon>
     <subtitle>The &lt;a href=&quot;http://www.paradiseridgewinery.com/&quot;&gt;Paradise Ridge Winery&lt;/a&gt; not only has great wines, but they also have a sculpture garden. We visited on 22 July 2007.</subtitle>
     <updated>2007-07-24T05:19:08Z</updated>
     <generator uri="http://www.flickr.com/">Flickr</generator>

     <entry>
        <title>IMG_0045.JPG</title>
        <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dorismith/882590644/in/set-72157600976524175/"/>
        <id>tag:flickr.com,2005:/photo/882590644/in/set-72157600976524175</id>
        <published>2007-07-24T05:19:08Z</published>
        <updated>2007-07-24T05:19:08Z</updated>
              <dc:date.Taken>2007-07-22T13:42:49-08:00</dc:date.Taken>
        <content type="html">&lt;p&gt;&lt;a href=&quot;http://www.flickr.com/people/dorismith/&quot;&gt;Dori Smith&lt;/a&gt; posted a photo:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://www.flickr.com/photos/dorismith/882590644/&quot; title=&quot;IMG_0045.JPG&quot;&gt;&lt;img src=&quot;http://farm2.static.flickr.com/1063/882590644_5a4a0d89f3_m.jpg&quot; width=&quot;240&quot; height=&quot;180&quot; alt=&quot; IMG_0045.JPG&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

</content>
        <author>
           <name>Dori Smith</name>
           <uri>http://www.flickr.com/people/dorismith/</uri>
                 </author>
        <link rel="enclosure" type="image/jpeg" href="http://farm2.static.flickr.com/1063/882590644_5a4a0d89f3_m.jpg" />
        <category term="winery" scheme="http://www.flickr.com/photos/tags/" />
        <category term="sonomacounty" scheme="http://www.flickr.com/photos/tags/" />
        <category term="sculptures" scheme="http://www.flickr.com/photos/tags/" />
        <category term="dorismith" scheme="http://www.flickr.com/photos/tags/" />
        <category term="paradiseridge" scheme="http://www.flickr.com/photos/tags/" />
        <category term="paradiseridgesculptures" scheme="http://www.flickr.com/photos/tags/" />
                 </entry>
     <entry>
        <title>IMG_0032.JPG</title>
        <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dorismith/882568164/in/set-72157600976524175/"/>
        <id>tag:flickr.com,2005:/photo/882568164/in/set-72157600976524175</id>
        <published>2007-07-24T05:15:14Z</published>
        <updated>2007-07-24T05:15:14Z</updated>
              <dc:date.Taken>2007-07-22T13:35:09-08:00</dc:date.Taken>
        <content type="html">&lt;p&gt;&lt;a href=&quot;http://www.flickr.com/people/dorismith/&quot;&gt;Dori Smith&lt;/a&gt; posted a photo:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://www.flickr.com/photos/dorismith/882568164/&quot;title= &quot;IMG_0032.JPG&quot;&gt;&lt;img src=&quot;http://farm2.static.flickr.com/1335/882568164_72eee9b41f_m.jpg&quot; width=&quot;240&quot; height=&quot;180&quot; alt=&quot;IMG_0032.JPG&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

</content>
        <author>
           <name>Dori Smith</name>
           <uri>http://www.flickr.com/people/dorismith/</uri>
                 </author>
        <link rel="enclosure" type="image/jpeg" href="http://farm2.static.flickr.com/1335/882568164_72eee9b41f_m.jpg" />

        <category term="winery" scheme="http://www.flickr.com/photos/tags/" />
        <category term="sonomacounty" scheme="http://www.flickr.com/photos/tags/" />
        <category term="sculptures" scheme="http://www.flickr.com/photos/tags/" />
        <category term="dorismith" scheme="http://www.flickr.com/photos/tags/" />
        <category term="paradiseridge" scheme="http://www.flickr.com/photos/tags/" />
        <category term="paradiseridgesculptures" scheme="http://www.flickr.com/photos/tags/" />
                 </entry>
</feed>

6.
var theText = tempDiv[1].innerHTML;
theText = theText.replace (/240/g,"75");
theText = theText.replace (/180/g,"75");
theText = theText.replace (/_m/g,"_s");



As previously mentioned, we only want half the <a> nodes, so we winnow out the ones here that we don’t want. In a file with information about 20 photos, there will be 20 <content> nodes, each of which contains two paragraphs. Each <content> node contains the photographer’s name (linked to their Flickr page), followed by an image that links to the Flickr-hosted version. We want just the latter, so we can just take the innerHTML from the second item in the tempDiv array, which gives us the <a> inside the paragraph (and the <img> tag it contains, as well).

Next, we’re using regular expressions to tweak the results. Flickr has sent us the tags for medium-sized version of the image, but we only want the thumbnail version. Because our images are either 240 wide by 180 tall or 180 wide by 240 tall (that is, they’re either horizontal or vertical), and we know the thumbnails are always 75 x 75, we just find any use of the numbers 240 or 180 in the text and change them to 75. We finish up by changing the image name itself; Flickr gives the medium-sized version a name that ends with _m, while the small version ends with _s, so we can just swap one for the other.

7.
document.getElementById("pictureBar").innerHTML += theText;



Inside the loop, we take the now-modified node that we want and then append it onto the HTML page’s pictureBar. The end result is as we see it in Figure 13.3 where every thumbnail image on the page is a link back to the full-sized version.

Figure 13.3. These thumbnail images were read from Flickr.


Getting Your Data

One of the things people want to do when they first hear about Ajax is write JavaScript that reads in all kinds of XML files (including RSS and Atom feeds), mash them up, and then put the results on their own Web page.

The bad news: it doesn’t quite work that way—a script can only read a file that comes from the same server as the one that the script is on itself. If you think about it for a while, you’ll start to figure out why; after all, if a script could read anything, then that would open up all kinds of possible security scams and fake sites.

The sort-of good news: you can have a program on your server that goes out periodically, grabs an XML file, and then stores it locally. Once you’ve done that, your Ajax application will have no problems reading it. In this example and the next, it’s assumed that you’ve got something running that grabs the Flickr data file of your choice periodically and saves it on your server. How to do that, though, is beyond the scope of this book.

The better news, though, is that you can (in some cases) use a script that’s hosted by the destination server itself—which can then read its own files, and report the results back to you. We’ll see an example of that shortly.


✓ Tips

  • While you can’t read a data file that’s stored on another server (see the “Getting Your Data” sidebar for more about why that’s the case), you can always have your HTML file load information from another server. Here, your Web page, no matter where it is, is able to display images from Flickr’s servers.

  • One of the best things about the Web 2.0 dot-coms is that they understand that people want access to data—and not just their own data, but other people’s data (when they’ve agreed to make it public) as well. For instance, it’s possible to search Flickr for all the photographs containing the tags “Hawaii” and “sunset,” and then get the result as an XML file. Combine that with this script or the next, and you’ll always have new and lovely photos on your page.


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

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