Evening Tip: Use jQuery To Retrieve Data From An XML File

In this quick tip, I’ll show you how to load data from an XML file onto a blank page. We’ll work with the $.get function and will also implement a loading gif while the information is being retrieved. We’ll be displaying a simple list of recommended web development books. Let’s go ahead and get started.

Step One: Review The Script

First, let’s take a look at our simple XML file. It merely contains a few books along with their title, image and description.

<?xml version="1.0" encoding="utf-8" ?>
<books>
    <book title="CSS Mastery" imageurl="images/css.jpg">
    <description>
    info goes here.
    </description>
    </book>

    <book title="Professional ASP.NET" imageurl="images/asp.jpg">
    <description>
    info goes here.
    </description>
    </book>

    <book title="Learning jQuery" imageurl="images/lj.jpg">
    <description>
    info goes here.
    </description>
    </book>
</books>

Next, let’s take a look at the actual jQuery.

    $(document).ready(function()
      {
        $.get('myData.xml', function(d){
        $('body').append('<h1> Recommended Web Development Books </h1>');
        $('body').append('
'); $(d).find('book').each(function(){ var $book = $(this); var title = $book.attr("title"); var description = $book.find('description').text(); var imageurl = $book.attr('imageurl'); var html = '<dt> <img class="bookImage" alt="" src="' + imageurl + '" /> </dt>'; html += '<dd> <span class="loadingPic" alt="Loading" />'; html += '<p class="title">' + title + '</p>'; html += '<p> ' + description + '</p>' ; html += '</dd>'; $('dl').append($(html)); $('.loadingPic').fadeOut(1400); }); }); });

Step Two: Decipher Time

Because this is a quick tip, I’ll run through the script a bit quicker than I usually would. When the document is ready to be manipulated, we’re going to fetch our XML file using the “$.get” function. In the parenthesis, we’ll pass in the location of the file, and then we’ll run a callback function. I’ll use the variable “d” to represent the information that was pulled from the XML file. Next, we’re going to create a heading tag and a definition list.

Continuing on, we’re going to search through the XML file (d) and find the tag entitled “book”. Referring back to my document, there are three books. Consequently, we’ll need to run the “each” method in order to perform an operation for each book. Remember, “each” is just like the “for” statements. It’s a way to run through each element in the wrapped set.

In the next block of code, I’m defining a few variables. In order to get the “title” and “description” from our XML file, we use “.attr(value)” – where “value” is equal to the attribute within the tag.

Lastly, we’re creating a variable called “html” that will contain the html that will display the information from our XML file. Merely assigning that information to the variable won’t display it on the page, however. To add it to the page, we grab the definition list and append the variable. – $(‘dl’).append($(html));

One more thing worth mentioning is that, while the information is being retrieved from the XML file, we’ll display a standard loading gif (via a background image). When the data has loaded, we’ll grab the image and fade it out.

You’re Done

I know I went through that somewhat quickly; So feel free to leave a comment and ask any questions that you might have. It should be noted that this script will require a bit more work before it becomes ready for a real world website. You have to compensate for people that have Javascript turned off. In this case, if they did have it off, they would be staring at a blank page. You must compensate for such things. But, I digress.

Related Posts

Add Comment

Discussion 68 Comments

Comment Page 2 of 2 1 2
  1. Dan says:

    What if the xml doc has 100 items and you only want the top 10?

  2. Gary Ricke says:

    Thanks!

    I tried 3 different jQuery samples and all failed in IE until this one.

    Cheers!

  3. Logan says:

    Like Ben, I would like to use this with a remote address. Is this possible? It doesn’t seen to work when I replace the local file with a URL.

  4. celco says:

    Hi thanks nettuts nice tutorial – question how do you add links in ht XML file to show up? is this the namespace issue or something else.

    All I want ot do is make the books as links…

    any help would be appreciated.

  5. JP says:

    Yes online demo works fine in IE7 but not offline. Why?

  6. Sagar S. Ranpise says:

    Awesome bro. Thanks a lot for sharing. Keep doing the good work..

    With Regards,
    Sagar S. Ranpise :-)

  7. ravi says:

    please let me know how to fetch the particular data from the xm. for example 2nd element from book note. please help its urgent

  8. bay says:

    This is Great!
    here’s a quick question..
    I’m very VERY new to all this…
    say if I have three buttons…each with ID 1, 2, and 3.
    I have an xml file with 3 different pieces of info each with an id of 1, 2, and 3 as well. How would I make a string that takes the id of the button…matches it to the ID of the xml…then spits out the corresponding info?

  9. Allen Mackley says:

    Jeffery, thank you for this great tip, it helped me out tremendously. I’ve got it working within my project, but there’s still a couple concepts I don’t quite understand.

    For example, why is the “d” necessary? What’s it stand for, what value is it and what’s exactly going on there?

    In your tip you say:
    “I’ll use the variable “d” to represent the information that was pulled from the XML file.”

    Could “d” be any other letter or word as well? Why do we need “d” to represent the file?

    The other question I have concerns this: “.append($(html));”
    I know what’s going on there for the most part, except I don’t understand why you need two pairs of parenthesis. Why is the extra pair necessary? (For example, would it work to just write “.append(html);” ?

  10. Nano says:

    Making Michael T’s and Mike’s script just a little bit better:

    replace:
    $(d).find(’book’).each(function()

    with:
    $(‘book’, d).each(function()

  11. bebeboo says:

    great post!

    i want to ask about this case, btw, if it’s not much trouble:

    say i have:

    lorem ipsum dolor hello world! lorem ipsum dolor et

    thisimage

    lorem ipsum dolor lorem ipsum dolor et

    i need to process each tag sequentially and output it in a similar way that a browser may output basic html tags (like anchors, spans, etc inside p tags)

    can i do that by just using for/each? or should i restructure my xml ?

    thank you in advance!

  12. bebeboo says:

    oops, tags not allowed, here it is:

    lorem ipsum dolor hello world! lorem ipsum dolor et

    thisimage

    lorem ipsum dolor lorem ipsum dolor et

  13. David says:

    Has anyone figured out how to load in an external file using a full URL (e.g. http://example.com/example.xml)?

  14. Andy says:

    I need to load two xml files on a single page. The second one is loaded depending on the data in the first one. I’m using the code above and the code seems to be conflicting . . . I can load only one XML file If I don’t load the first one the second one loads fine.

    Please help

  15. Kency says:

    it good tip but not work on IE
    my OS is windows 7 anh i use Expression web compile code
    anh when i run this code
    it work fine on Firefox but IE notwork

Comment Page 2 of 2 1 2

Add a Comment