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('
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.



Good idea i like it. I might use this for a project
JQuery is so powerful & dynamic.
I think I’m in love.
Keep these JQuery tuts coming!
Great Tip! :)
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.
It’s a tip, not a tut.
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.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.Just what I was after! Thanks guys! I like the format of having some smaller ‘evening tips’ style tuts! Keep up the good work!
Great tip :D jQuery is brilliant for little things like this
Thanks for the tip!
BTW, I think maybe you didn’t close an em tag or something? Everything’s in italics!
Wow thanks! This is actually very very valuable code!
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!
this would of been helpful this morning when I was dealing with this. For now on I check nettuts before going into work.
When did the comments go italicized?
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!
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?
@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.
@Brian – It isn’t required…but is usually considered to be a good practice. It reminds us that we’re dealing with jQuery.
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.
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
Great, now a tut that will help to parse xml as html.
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?
I love you for this great post ;D
Cool gonna try iy out soon!
@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.
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
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() + ”);
});
});
});
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>’);
});
});
});
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/)
@Khaled – I just checked the demo in IE7 and IE6. It works just fine. Am I missing something? Anybody else notice anything?
Don’t try the demo on nettuts … try it on your pc … download the demo and try it on your pc without a server
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?
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.
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.
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/
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/).
When i clicked on this i didn’t think it would be helpful but it actaually was thanks NETTUTS
Using this right now – making a template for TF!! … Thanks Jeffrey! :)
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() + ‘ ‘);
});
});
});
Or … not. Looks like the form validation script ate it.
What about saving data into a XML file?
Or isn’t that possible with just client-based scripts?
I do not believe this
Awesome tutorial! But what would it take to add a set of navigational buttons via the xml file?
This is a very nice tip. But do anyone know how to access XML namespaces?
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
this is wonderful tutorial i will put acopy of this lesson on
my site here
http://www.as7ap4you.com
@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”);
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.
online demo works but not offline ie7
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?