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.




RoyalSlider – Touch-Enable ... only $12.00 
What if the xml doc has 100 items and you only want the top 10?
Fix for IE
http://stackoverflow.com/questions/436670/local-html-file-ajax-call-and-jquery-woes
Thanks!
I tried 3 different jQuery samples and all failed in IE until this one.
Cheers!
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.
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.
Yes online demo works fine in IE7 but not offline. Why?
Awesome bro. Thanks a lot for sharing. Keep doing the good work..
With Regards,
Sagar S. Ranpise :-)
please let me know how to fetch the particular data from the xm. for example 2nd element from book note. please help its urgent
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?
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);” ?
Making Michael T’s and Mike’s script just a little bit better:
replace:
$(d).find(’book’).each(function()
with:
$(‘book’, d).each(function()
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!
oops, tags not allowed, here it is:
lorem ipsum dolor hello world! lorem ipsum dolor et
thisimage
lorem ipsum dolor lorem ipsum dolor et
Has anyone figured out how to load in an external file using a full URL (e.g. http://example.com/example.xml)?
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
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
i find the way to fix for IE
http://rationalogic.com/development/jquery-ajax-and-internet-explorer/
Read it!!!!
@David – you can’t use a URL that isn’t on your domain with AJAX–being able to do so would represent a potential security problem. You can get around this with a “proxy” server-side script–a server side script that fetches content from an external URL and makes it available to the JS on your domain.
jFeed uses a proxy.php file and has several examples: http://plugins.jquery.com/project/jFeed
I’m using the above in 2 js files, on the same page, with different “place-holders” (id=x-place-holder & id=y-place-holder), slightly different xml files and display routines. I’ve changed all vars except “html”. When the 2nd file runs it creates a duplicate in the other-place-holder, not called in the function. Does ajax have some kinda global scope or something??? (http://gracehappens.net)
Oops…. http://gracehappens.net/_GC3/
good demo…help me a lot…..thnkx for sharing
First the admission, i’m a noob with jQuery,
what i’m doing: i have a project i made in flash that uses data from an xml file to create a simple slide show to showcase items and it’s pretty simple, Image, 3-5 lines of text, and a URL. (for this instance URL is irrelevant as this client doesn’t want unique URLs) Instead of unique URLs, each image clicks through to a simple webpage i’m creating. In order to save myself time i’m trying to implement a solution like the one above. I’ve gone through many and this seems to be the most efficient. My goal is to use the exact same XML file for the flash execution and the web execution so i don’t have to hand code this in html… Only one problem.
line 1
line 2
line 3
line 4
images/css.jpg
this is the XML, with just one slide for testing purposes. All the text shows up fine, but i cannot seem to figure out how to get the picture to show up when I alter the xml from an attribute to a child element of the parent slide.
$(document).ready(function()
{
$.get(‘myData.xml’, function(d){
$(‘body’).append(”);
$(d).find(‘book’).each(function(){
var $book = $(this);
var line1 = $book.find(‘line1′).text();
var line2 = $book.find(‘line2′).text();
var line3 = $book.find(‘line3′).text();
var line4 = $book.find(‘line4′).text();
var pic = $book.find(‘pic’).text;
var html = ‘ ‘;
html += ‘ ‘ + line1 + ” + line2 + ” + line3 + ” + line4 + ” ;
html += ”;
$(‘dl’).append($(html));
});
});
});
thanks!
here’s XML formated correctly for the blog display:
< slide>
< line1> line 1 </line1>
< line2> line 2 </line2>
< line3> line 3 </line3>
< line4> line 4 </line4>
< pic>images/css.jpg</pic>
< /slide>
< /slides>
And the JS correctly formatted:
< script type=”text/javascript”>
$(document).ready(function()
{
$.get(‘myData.xml’, function(d){
$(‘body’).append(‘< dl />’);
$(d).find(‘book’).each(function(){
var $book = $(this);
var line1 = $book.find(‘line1′).text();
var line2 = $book.find(‘line2′).text();
var line3 = $book.find(‘line3′).text();
var line4 = $book.find(‘line4′).text();
var pic = $book.find(‘pic’).text;
var html = ‘< dt> < img class=”bookImage” alt=”" src=”‘ + pic + ‘” /> < /dt>’;
html += ‘< p> ‘ + line1 + ” + line2 + ” + line3 + ” + line4 + ‘< /p>’ ;
html += ‘< /dd>’;
$(‘dl’).append($(html));
});
});
});
< /script>
I get the code in example, I can run demo online but I cannot run code offline. Who can tell me the reason why it goes.
Thks
It works well on Firefox offline. Why does not work on IE offline?
Thx
Cuong
Fantastic beat ! I wish to apprentice at the same time as you amend your site, how could i subscribe for a weblog site? The account aided me a acceptable deal. I were a little bit acquainted of this your broadcast provided vibrant clear concept
How can make image thumb link?
In this link “What’s new in web” section i am using That script, now data is loading from XML file, i want thumb link, any one can help?
http://viewgraphic.net/demo/sunshine/
This is image url
var imageurl = $project.attr(‘imageurl’);
I want a hyper link to this image, how to call link for this code?
Thanks