I have an XML file with this structure:
<?xml version="1.0" encoding="utf-8" ?>
<Photobank>
<Landowner Name="Arnoldo">
<Photo>
<Animal>Jaguar</Animal>
<Category>Cat</Category>
<Image>Charlie_20111120_010500.JPG</Image>
</Photo>
<Photo>
<Animal>Tapir</Animal>
<Category>Prey</Category>
<Image>Charlie_20111120_010500.JPG</Image>
</Photo>
</Landowner>
<Landowner Name="Charlie">
<Photo>
<Animal>Margay</Animal>
<Category>Cat</Category>
<Image>Charlie_20111120_010500.JPG</Image>
</Photo>
<Photo>
<Animal>Tayra</Animal>
<Category>Prey</Category>
<Image>Charlie_20111120_010500.JPG</Image>
</Photo>
</Landowner>
</Photobank>
And I would like for my page to parse and format all the photos for one landowner on the initial page load, and then empty the div and fill it with a different landowner’s photos when hitting buttons. So far, I am able to parse the XML and get the proper landowner’s photos on initial load, but I’m having trouble writing the function so that I can also use it to show the photos of other landowners.
Here is the jQuery Ajax:
$.ajax({
type: "GET",
url: "xml/photobank.xml",
dataType: "xml",
success: xmlParser
});
function xmlParser(xml) {
$('#photo_container').empty();
console.log('1');
$(xml).find('Landowner').each(function(){
console.log('2');
var landownerName = $(this).attr('Name');
if (landownerName==="Charlie") {
$(this).find('Photo').each(function(){
$("#photo_container").append('<div class="photo ' + $(this).find("Category").text().toLowerCase() + '"><p>' + $(this).find("Animal").text() + '</p>'+ '<img class="photobank" src="images/' + $(this).find("Image").text() + '" />' + '</div>');
})
}
});
}
I would like to replace ==="Charlie" in xmlParser with a variable that the function uses as an argument, but every time I try to add arguments to the function declaration, the initial Ajax load stops working. Any hints?
The code on my development page below attempts to use the “Arnoldo” button to switch the content, but I couldn’t get too far. I am also open to using different methods to achieve this (non-Ajax, JSON?) if that would be better. I just want it to be easy for others to add photo information in the future.
Live example:
HTML: http://lamanai.org/catmap/index.html
JS: http://lamanai.org/catmap/js/cameramap.js
XML: http://lamanai.org/catmap/xml/photobank.xml
Update: ShankarSangoli below has helped me form the function the way I would like to, but now my initial Ajax call does not work. I get Uncaught Error: Invalid XML: [object Document] in the console. I imagine I am calling the Ajax at the wrong time (currently on document ready). Any ideas? See live page linked above.
You should parse the xml using
$.parseXMLbefore using it. You can have an anonymous success handler and then callxmlParserpassing the xml data and another parameter.Reference: http://api.jquery.com/jQuery.parseXML/