Pull XML into a table with filtering in jQuery
Now we’re getting into more complex territory, this small project pulls in data from an XML file and feeds it into a table in your page, this XML can be either a server side script, or a feed, or just a static XML file. You wouldn’t want to do this on your main site as search engine’s wouldn’t be able to spider the table, but it’s really useful for dashboards, statistics, admin pages, etc. You can filter the XML without reloading either the XML or the page.
Example demo XML table with filtering
Download Files (5Kb)
This is the XML for the table we want to display. It’s standard looking XML, and you can and should have multiple items within your data tag.
Griffith Gibbs 03009 725685 UK
The HTML looks like this.
Selection: ALL UK USA
| Name | Telephone | Country |
|---|
To simplify the code, we have the filters already built in the HTML using radio buttons, on the radio button change, we call a changeFilter function to change the table. Below the radio buttons you have the table itself with table headers hard coded. Of course you could build the filters and table headers from the xml, but I did it this way for simplicity.
The jQuery is below. We use global variables for country and data as we need to pass those into callbacks. It’s all commented, so download the example and have a look.
var $country=""; //globals as we have callbacks that need this data.
var $xmldata="";
$(document).ready(function(){
$.ajax({ //get the XML data
url: "xmlfiltering.xml", //URL to get the data from
success: loadTable //callback on success
});
});
function changeFilter(ctry){
$country=ctry; //set global country variable to changed country
$(".datarow").remove(); //clear table
loadTable($xmldata); //rebuild
}
function loadTable(data){
$xmldata=data; //set our global XML variable to the data from the callback for re-use later.
$(data).find("item country:contains('"+$country+"')").parent().each(function(){ //find each row in the XML with the country we want to show.
var $this=$(this); //cache selector
var $name=$this.find("name").text(); //get name
var $tel=$this.find("tel").text(); //get telephone
var $country=$this.find("country").text(); //get country
$("#datatable").append("
"+$name+"
"+$tel+"
"+$country+"
"); //output table row
});
zebraStripe();
}
//function from previous tutorial with minor change to selector to zebrastripe the table.
function zebraStripe(){
$("#datatable").each(function(){
var $s=0;
$(this).find("tr").each(function(){
var $t = $(this).children("td");
$s++;
if($s%2==1)
$t.addClass("stripe");
else
$t.removeClass("stripe");
});
});
}
Hope you found this useful. Please download the example and use it yourself if you do.