0

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
            });
        }
    });
});
Ty Bailey
  • 2,392
  • 11
  • 46
  • 79

1 Answers1

-1

You shouldn't be making an AJAX call in an iteration - instead you could iterate through your cookieVal and make an array of nodeID's to send to the server side script and return an array.

For example:

var finalArray = [];
var sendArray  = [];

jQuery.each(cookieVal, function(i, v) {
    sendArray.push(i);
});

jQuery.ajax({
        type: "POST",
        url: ajaxurl,
        data: {action: "get_scheduled_info", data: sendArray},
        success: function(data) {

            var eventData = JSON.parse(data);
            var sDisplayTime = eventData.start_time;
            var eDisplayTime = eventData.end_time;

            // Loop round each item and add it to finalArray
        }
    });

This will save a lot of requests and allow you to handle the response properly.

The above code is just an example so it is untested.

Let me know if you have any questions.

David Jones
  • 4,275
  • 6
  • 27
  • 51