I am making some application that it loads data from an xml file. it works file if there is one corresponding div structure and one xml path. But I want to have multiple copies of my div structure, but each one will load different xml content. I tired to do it by loop but it does copy each data in both content.
JSFIDDLE: https://jsfiddle.net/danials/1g2w3sf7/
HTML:
<div class="data" data-xml="https://dl.dropboxusercontent.com/u/33538012/file1.xml">
</div>
<div class="data" data-xml="https://dl.dropboxusercontent.com/u/33538012/file2.xml">
</div>
jQuery:
$(".data").each(function() {
var path = $(this).attr("data-xml");
$.ajax({
url: path,
dataType: "xml",
success: parse,
error: function() {
alert("Error: Something went wrong with loading the playlist!");
}
});
});
function parse(document) {
$(document).find("person").each(function() {
$(".data").append(
"<div class='name'>Name: " +
$(document).find("name").text() +
"</div><div class='title'>Title: " +
$(document).find("title").text() + "</div>")
//$(document).find("name").text();
});
}
As you can see in the HTML I have exactly the same structure but each one are linked to a different xml file paths., an in my code I want to load the corresponding data based on the xml file they are linked to.
UPDATE:
Based on the answer @charlietfl has provided, the code seems better now, but still does not provide the intended result. I have been testing on the below code, and realised that it does not pass the xml instance to the parse
function.
$(".data").each(function() {
// store element instance
var elem = $(this);
var path = $(this).attr("data-xml");
//console.log($el);
$.ajax({
url: path,
dataType: "xml",
success: function(xml){
parse(document, elem);
},
error: function() {
alert("Error: Something went wrong with loading the playlist!");
}
});
});
function parse(document, elem) {
console.log($(document).find("name").text());
$(document).find("person").each(function() {
//alert($el);
var $person = $(this);
elem.append(
"<div class='name'>Name: " +
$person.find("name").text() +
"</div><div class='title'>Title: " +
$person.find("title").text() + "</div>")
});
}
Any idea?
This should do it. You need to store the instance of element outside the ajax and pass that into the success handling
$(".data").each(function() {
// store element instance
var $el = $(this),
path = $(this).attr("data-xml");
$.ajax({
url: path,
dataType: "xml",
success: function(xml) {
parse(document, $el);
},
error: function() {
alert("Error: Something went wrong with loading the playlist!");
}
});
});
function parse(document, $el) {
$(document).find("person").each(function() {
var $person = $(this);
$el.append(
"<div class='name'>Name: " +
$person.find("name").text() +
"</div><div class='title'>Title: " +
$person.find("title").text() + "</div>")
});
}