Why doesn’t this work?
var myData;
function getData()
{
$.ajax(
{
url: dataURL,
success: function(data)
{
myData = data;
}
}
);
}
getData();
console.log(myData);
I’m scoping the variable correctly, but I can’t use the data outside the function..
AJAX is asynchronous. It runs in the background while you code is running. So, when you’re calling
console.log(myData);, the AJAX call isn’t done yet, so the variable isn’t set.You should use the callback function to process the data, like so: