I have a JSON object containing IDs of data stored in a MySQL database. I am looping through the JSON object and sending the IDs via ajax to the database to return the data associated with that ID.
In that loop, after the data is returned, I am attempting to save that data to an array using:
finalArray.push({
'nodeID' : nodeID,
'startTime' : sDisplayTime,
'endTime' : eDisplayTime
});
The data gets put into the array and I can use console.log(finalArray);
while in the loop to see it put out the correct data. My problem is I cannot access the entire array outside of the loop. There should be 3-5 keys in the array when the loop is finished and the final output should include everything returned. When I call console.log(finalArray);
outside of the loop I get a blank []
in the console.
I am declaring the finalArray = [];
array outside/before the loop even starts so I wouldn't think the scope is an issue.
When I do it like finalArray = { event: [ ] }
and then populate the data like:
finalArray.event.push({
'nodeID': nodeID,
'startTime': sDisplayTime,
'endTime': eDisplayTime
});
I can console.log(finalArray);
outside the loop and see the data. Unfortunately, I need this in a format I can use the sort()
function on so this way won't work.
Would anyone happen to know why I can't access the array outside of the loop with the first method?
Here is the loop (simplified for display):
finalArray = [];
jQuery.each(cookieVal, function(i, v) {
var nodeID = i;
jQuery.ajax({
type: "GET",
url: ajaxurl,
data: "action=get_scheduled_info&nid=" + nodeID,
success: function(data) {
var eventData = JSON.parse(data);
var sDisplayTime = eventData.start_time;
var eDisplayTime = eventData.end_time;
finalArray.push({
'nodeID': nodeID,
'startTime': sDisplayTime,
'endTime': eDisplayTime
});
}
});
});