Reputation: 1447
I have this code:
$.ajax({
url: "lang_files/" + window.localStorage.language + ".xml",
dataType: 'xml',
success: function(data) {
var xml_node = $("resources", data);
$("#index_intro").text(xml_node.find('string[name="index_intro"]').text());
},
error: function(data) {
console.log("Error loading XML data");
}
});
It works fine, the .text() is set properly using the information from my XML file, I now want to be able to use the XML file across my application, and not just inside the success call, so I did:
var xml_node;
$.ajax({
url: "lang_files/" + window.localStorage.language + ".xml",
dataType: 'xml',
success: function(data) {
xml_node = $("resources", data);
},
error: function(data) {
console.log("Error loading XML data");
}
});
$("#index_intro").text(xml_node.find('string[name="index_intro"]').text());
This is not working though, I would like to understand why.
Upvotes: 0
Views: 281
Reputation: 74420
This is because ajax is asynchronous so at time you call xml_node, it is still undefined. Try this instead:
$.ajax({
url: "lang_files/" + window.localStorage.language + ".xml",
dataType: 'xml',
success: function(data) {
setIndexIntro($("resources", data));
},
error: function(data) {
console.log("Error loading XML data");
}
});
function setIndexIntro(xml_node)
{
$("#index_intro").text(xml_node.find('string[name="index_intro"]').text());
}
Upvotes: 2