I’m having problems getting the returned array from a return ajax callback function which is inside of another function. The problem being no array data is being received during the first cycle…..
var testFile = $("#selection").val();
var testData = getTestData(testFile);
alert(testData); // not working during the first time I run the function, empty
function getTestData(testF)
{
var testArray = [];
$.getJSON("test.php",{fileTest: testF}, function(data)
{
$.each(data, function(index, value)
{
if(value == "")
{
}else
{
testArray[index] = value;
}
}
});
alert(testArray); // working I see the values
return testArray; // not working the first time running this function
}
Ajax calls are asynchronous. What does that mean?
When you call
$.getJsonjust starts the HTTP request, it does not immediately fill intestArray. Instead, it fills intestArrayat some unspecified point in the future after the HTTP request has completed.The reason you see one of the alerts but not the other is simple: By the time you click on the ‘OK’ button for the first alert, the request has finished and your answer is ready. I’m willing to bet that the first alert that you’re seeing (that fails) is actually the one inside
getTestData. Here’s the likely sequence of events:getTestData()$.getJSON()alert(testArray)inside getTestData is called, displaying an alert. SincetestArrayhasn’t been filled in yet, you have an empty array.$.getJSON()call completes and fills outtestArray.return testArray;is run, returning the filled-in valuesalerton line 3 is run, showing the array