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.
Evening Tip: Use jQuery To Retrieve Data From An XML File
Aug 14th in JavaScript & AJAX by Jeffrey WayStep 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('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
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.












User Comments
( ADD YOURS )Taylor Satula August 14th
Good idea i like it. I might use this for a project
( )Chris August 14th
JQuery is so powerful & dynamic.
I think I’m in love.
Keep these JQuery tuts coming!
( )Philo August 14th
Great Tip!
( )anonymous coward August 14th
seems like these tutorials are getting lame. if you don’t have to write a full article, don’t publish it. And certainly don’t spend time in your already über short drivel telling me how quick and short this will be.
( )Graham Reeds April 2nd
It’s a tip, not a tut.
( )Brian August 14th
This might be a basic question (I’m still getting my feet wet with Javascript), but why is the
( )$bookvariable preceded by a dollar sign? I suspect it has something to do with the jQuery function.Sean McArthur August 14th
Interesting how jQuery does it. I actually find jQuery a little too cryptic for my tastes. It feels too easy to jam so much into a single line; code becomes harder to read. Mootools and Prototype both have pretty ways of accessing AJAX.
Ps. You got a run-away
( )emtag making the rest of the page in italics.George Burrell August 14th
Just what I was after! Thanks guys! I like the format of having some smaller ‘evening tips’ style tuts! Keep up the good work!
( )Ben Griffiths August 14th
Great tip
jQuery is brilliant for little things like this
( )Dan Harper August 14th
Thanks for the tip!
( )Dan Harper August 14th
BTW, I think maybe you didn’t close an em tag or something? Everything’s in italics!
( )Ronny-André August 14th
Wow thanks! This is actually very very valuable code!
( )Vin Thomas August 14th
Holy Moly! I love this stuff! I am just learning jquery and I can’t get enough of it. It is winning the javascript war in my books!
Thanks a ton for all your great tips! I REALLY appreciate it!
( )Braden Keith August 14th
this would of been helpful this morning when I was dealing with this. For now on I check nettuts before going into work.
( )Braden Keith August 14th
When did the comments go italicized?
( )Zach Dunn August 14th
I get terribly excited when I see jQuery on my RSS feed. When it turns out to be useful? That’s double the excitement. Great tutorial!
( )Dan August 14th
What’s the point of using XML? Couldn’t you just as easily hard code that or stick it in a database?
*Confused*
Also, where are those weekly PHP tutorials?
( )Jeffrey Way August 14th
@Dan – Ahh, sorry about that. It’s been fixed.
@The Other Dan – In this situation – yeah, you could just hard-code it. But what about if you were pulling from an RSS file…or something similar? The example is intentionally simple – but the uses are widespread.
( )Jeffrey Way August 14th
@Brian – It isn’t required…but is usually considered to be a good practice. It reminds us that we’re dealing with jQuery.
( )Connor August 14th
Man this is very useful. Right now I’m working on a flash calendar that runs off an xml page. Now, I could be super accessible and create a non flash version that runs off the same sheet using JQuery.
( )mattems August 14th
awesome..simple and to the point, definately not for the novice javascripter as the explanation is low. But i loved it.
“This might be a basic question (I’m still getting my feet wet with Javascript), but why is the $book variable preceded by a dollar sign? I suspect it has something to do with the jQuery function.”
definately a typo, obviously a php developer
rock on
( )Tom August 14th
Great, now a tut that will help to parse xml as html.
( )Shane August 14th
Interesting stuff. I’ve never done this with jQuery and XML – I’m sure it’ll come in use some time in the near future.
Just one thing – that second book – ASP.NET – what’s that?
Any plans for ASP.NET tutorials on the site?
( )BroOf August 15th
I love you for this great post ;D
( )Jaswinder Virdee August 15th
Cool gonna try iy out soon!
( )Jeffrey Way August 15th
@Shane – I’d love to have ASP.NET tutorials. It’s my framework of choice. But, I’m not sure that there is enough of a demand for it. If enough people asked for them, I would absolutely get some up.
( )Damien August 15th
Some simple asp.net tutorials would be ace, I like this how would extending this work though so that it could fall over ok without js??
Cheers
Damien
( )Michael Thompson August 15th
Several things…
First: you don’t need the full $(document)…bit, just pass the function to an empty jQuery call:
$(function() {
// … do stuff when the DOM is ready …
}
Second: the loading icon should be attached to the body BEFORE you do anything. Then load the XML, parse it, drop the content into your DL and remove the loading animation. Adding the loading animation at the same time you’re adding the content to which it is a metaphor for loading makes the loading icon unneccessary as you’re seeing it AFTER the content has been loaded and added to the page.
Third: accessing an attribute, storing it in a variable and then retrieving the value is far more expensive than just accessing the attribute. Several of the variable definitions are unnecessary.
Fourth: instead of wasting time building a string, passing it to jQuery, having jQuery expand it and append each item, just append the items as necessary.
Here’s a cleaned-up version:
$(function() {
$.get(’myData.xml’, function(d){
$(’body’).append(’Recommended Web Development Books’);
$(d).find(’book’).each(function(){
var book = $(this);
$(’dl’)
( ).append(” + book.attr(’title’) + ”)
.find(’dd’)
.append(”)
.append(” + book.attr(’title’) + ”)
.append(” + book.find(’description’).text() + ”);
});
});
});
Michael Thompson August 15th
Sorry, forgot to escape my gt/lt:
$(function() {
$.get(’myData.xml’, function(d){
$(’body’).append(’<h1>Recommended Web Development Books</h1><dl></dl>’);
$(d).find(’book’).each(function(){
var book = $(this);
$(’dl’)
( ).append(’<dt>’ + book.attr(’title’) + ‘</dt><dd></dd>’)
.find(’dd’)
.append(’<img class=”bookImage” alt=”" src=”‘ + book.attr(’imageurl’) + ‘” />’)
.append(’<p class=”title”>’ + book.attr(’title’) + ‘</p>’)
.append(’<p>’ + book.find(’description’).text() + ‘</p>’);
});
});
});
Khaled August 15th
Hello,
nice tut, but it’s not working in IE and it’s a shame for jQuery that XML parsing is not working well for IE. I’ve talked to some jQuery folks @IRC and they told me the same thing … it’s kind of shortage … and for that there exists a class named: XML2JSON (www.fyneworks.com/jquery/xml-to-json/)
( )Jeffrey Way August 15th
@Khaled – I just checked the demo in IE7 and IE6. It works just fine. Am I missing something? Anybody else notice anything?
( )Khaled August 15th
Don’t try the demo on nettuts … try it on your pc … download the demo and try it on your pc without a server
( )Ben August 15th
What about CData? I’m using an xml file for my flash content and cdata in order to have some formatting – I’d then like to use the xml content as alternative content for the flash. But it seems that any js xml retriever fails when it hits the Cdata. Any Tips?
( )Mike Bobiney August 15th
Demo works fine for me.
If this were put to actual use I might have added a css class to the dl element to prevent from accidentally selecting multiple occurrences.
( )Zarathustra August 16th
Could someone talk me/us through the process of parsing a Flickr xml feed using this principle? I am trying without much success. With this extra example in the thread I am sure many people would benefit. Thanks a lot.
( )Zarathustra August 16th
This script has “done the job” for me (on a non-wordpress site btw). But as (as usual!) I wish I understood it better. Still, a walkthrough of using jQuery to manipulate a Flick feed would be a great tutorial. And definitely more “real world” useful than your example above, although I understand it was a quick tip
Link: http://www.nulldevice.de/2008/05/flickr-rss-feed-plugin-for-jquery-and-wordpress/
( )Milinda August 18th
According to my experience jQuery can’t handle XML with namespaces(namespaces handling is a must when it comes to web services related interactions). Currently Firefox and IE handle XML with namespaces in two different ways and jQuery can’t handle that. I have blogged about this problem here(http://mpathirage.com/why-most-popular-javascript-libraries-doesnt-support-xml-with-namespaces/). And the solution is available here(http://mpathirage.com/solution-to-xml-namespace-problem-in-getelementsbytagname/).
( )Taylor Satula August 21st
When i clicked on this i didn’t think it would be helpful but it actaually was thanks NETTUTS
( )James August 21st
Using this right now – making a template for TF!! … Thanks Jeffrey!
( )Mike August 24th
Here’s Michael T’s code from above reformatted slightly so it works with the rest of the demo:
$(function()
{
$.get(’myData.xml’, function(d)
{
$(’body’).append(’Recommended Web Development Books’);
$(d).find(’book’).each(function()
{
var book = $(this);
$(’dl’)
( ).append(” + ” + ”)
.append(’ ‘ + book.attr(’title’) + ‘ ‘ + book.find(’description’).text() + ‘ ‘);
});
});
});
Mike August 24th
Or … not. Looks like the form validation script ate it.
( )alterIdealism August 29th
What about saving data into a XML file?
( )Or isn’t that possible with just client-based scripts?
fornetti August 30th
I do not believe this
( )Miguel September 10th
Awesome tutorial! But what would it take to add a set of navigational buttons via the xml file?
( )Aamir Afridi September 16th
This is a very nice tip. But do anyone know how to access XML namespaces?
( )Ng Xuan Mui October 20th
nice. But if data return is xml (not in a file), how do U process ? I test in IE6, if I read a xml file, no prob, but when I test on data return, it’s xml, too, but nothing appear
Thanks for ur solution
( )kareem November 24th
this is wonderful tutorial i will put acopy of this lesson on
( )my site here
http://www.as7ap4you.com
Jimmy December 6th
@mattems and Brian
I don’t think adding a dollar sign in front of the variable is a typo. I thought it was too when I first saw this practice, and it does seem php related, but I’ve seen it being used in jQuery scripts pretty frequently. It’s just is an easy way of distinguishing between variables.
Most variables will be a string or a number maybe, but by adding the dollar sign, you can be clear that it’s a jQuery object being stored there (if you stick to the practice). You can still access all your usual jQuery functions, but from an easier to read (and more visually appropriate with the $) variable.
e.g.
( )var $navitem = $(”#nav li:first”);
$listitem.fadeOut(”slow”);
Chris Tolbert January 13th
Great tutorial, I had a hard time doing something similar on my page to make a easy updatable catalog of cd’s, so that anyone could add their cd to the list. You’ve just made my life easier.
( )anemia January 31st
online demo works but not offline ie7
( )Ben February 3rd
Hi there,
Thanks for the tutorial, but I was wondering is it possible to load XML generated by a servlet? So there is no myData.xml just a URL?
( )Dan February 3rd
What if the xml doc has 100 items and you only want the top 10?
( )Vahid February 4th
Fix for IE
( )http://stackoverflow.com/questions/436670/local-html-file-ajax-call-and-jquery-woes
Gary Ricke February 5th
Thanks!
I tried 3 different jQuery samples and all failed in IE until this one.
Cheers!
( )Logan February 5th
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.
( )celco February 18th
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.
( )JP February 19th
Yes online demo works fine in IE7 but not offline. Why?
( )Sagar S. Ranpise February 20th
Awesome bro. Thanks a lot for sharing. Keep doing the good work..
With Regards,
( )Sagar S. Ranpise
ravi March 22nd
please let me know how to fetch the particular data from the xm. for example 2nd element from book note. please help its urgent
( )bay May 23rd
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?
Allen Mackley June 21st
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);” ?
Nano September 30th
Making Michael T’s and Mike’s script just a little bit better:
replace:
$(d).find(’book’).each(function()
with:
( )$(’book’, d).each(function()
bebeboo October 15th
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!
( )bebeboo October 15th
oops, tags not allowed, here it is:
lorem ipsum dolor hello world! lorem ipsum dolor et
thisimage
lorem ipsum dolor lorem ipsum dolor et
( )