I’m a js/jquery noob and have been struggling to get an anonymous function to work as a regular function. Could someone point out what I’m doing wrong?
Here’s what’s taken me a few hours:
var tracklist = new Array();
function stuffXML(xml) {
$(xml).find('track').each(function(){
var logo = $(this).find('logo').text();
var location = $(this).find('location').text();
var id = $(this).find('identifier').text();
var info = $(this).find('info').text();
var title = $(this).find('title').text();
var creator = $(this).find('creator').text();
tracklist.push(logo,location,id,info,title,creator);
});
console.log('mid' + tracklist); //works here
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "real.xml",
dataType: "xml",
success: stuffXML
});
console.log(tracklist); //but not here - empty array
});
I’m trying to parse the list (a bunch of images & text for a slideshow) into an array (successful there) and then have them available but my scope is clearly too confined. I can’t see what I’m doing wrong tho…
Any help would be appreciated…
Your problem is just that you’re forgetting what the A in AJAX stands for. Asynchronous. When you run the command for
It runs it immediately, without hesitation, and follows it up immediately with your console.log. In the background, the browser is busy making a request for the data and then adding it to your tracklist variable. So, what you want to do is put that console.log inside of stuffXML. Granted, you probably want to do other things than console.log.. so, have the ‘stuffXML’ fire off any other events you need to fire to get the rest of your code doing what it needs to do. Just remember that a web server isn’t going to serve a request to your page faster than javascript is going to get to the next line of code to execute.