I have some jQuery with an Ajax call that looks like this:
$.ajax({
type: "GET",
url: "xml/photobank.xml",
dataType: "xml",
success: function(xml){
xmlParser(xml, "Charlie");
}
});
function xmlParser(xml, landOwner) {
//Initial photos do not load if following line is used.
//xml = $.parseXML(xml);
$('#photo_container').empty();
console.log('1');
$(xml).find('Landowner').each(function(){
console.log('2');
var landownerName = $(this).attr('Name');
if (landownerName === landOwner) {
$(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>');
})
}
});
}
You can see the XML file here: http://lamanai.org/catmap/xml/photobank.xml
However, the Ajax does not display the parsed XML, and throws this error in Chrome’s console: Uncaught Error: Invalid XML: [object Document]. Am I calling the Ajax at the wrong time? Right now it is on document ready, since I need the initial “Charlie” category parsed on the initial page load.
If I remove the xml = $.parseXML(xml); line, the initial parsed XML does load, but then I get Uncaught ReferenceError: xml is not defined errors when trying to use the xmlParser function afterwards.
Any hints? This is my first encounter with Ajax.
HTML: http://lamanai.org/catmap/
JS: http://lamanai.org/catmap/js/cameramap.js
XML: http://lamanai.org/catmap/xml/photobank.xml
—
Update: The xml = $.parseXML(xml); line was removed, but now I’m having trouble re-using the function. The following code results in xml is not defined errors.
$('#btn_arnoldo').click(function(){
xmlParser(xml, "Arnoldo");
});
I can use the following Ajax call instead, and have it work, but is it really necessary to do the Ajax each time I want to switch what part of the XML I want to use? I thought the initial Ajax gives me an object that I can parse from?
$('#btn_arnoldo').click(function(){
$.ajax({
type: "GET",
url: "xml/photobank.xml",
dataType: "xml",
success: function(xml){
xmlParser(xml, "Arnoldo");
}
});
});
It looks like it is already parsed. Your xml object seems to contain an xml document already, while parseXML is supposed to be used to convert an XML string to an XML document. If you want to access all the Image tags, you should be able to use jQuery to iterate all of them using each.