0

I'm using AJAX to parse json, everything works fine although when I try to call a function where I pass on the index value of the loop and then the funcion pushes this value into the Global array, It seems like it's not pushing these values even though console.log() prints out everything as it should on each step yet when I check the array length it's always at 0.

//This bit of code is actually inside a function and another ajax success   
$.each(updatedData, function(index, element) {

          $.ajax({ 
           type: 'GET', 
           url: 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&format=json&redirects&callback=?&titles='+updatedData[index], 
           data: { get_param: 'value' }, 
           dataType: 'json',
           success: function (data) { 
                   console.log('success wiki');
                   //getting the pagenumber key value to use the extract value from it
                   var pagenum = Object.keys(data.query.pages);


                   if(data.query.pages[pagenum[0]].extract == null)
                   {
                     recycleData(index);
                   }

            }

    });

   });


//this is the function which should push the trash value to the trashData 
//the console.log actually logs all the correct values yet still doesn't push
function recycleData(trash){
console.log("sliced - "+trash);
trashData.push(trash);
}


//that's how the array is defined, it's obviously defined before all the functions just in case someone would ask
var trashData = [];

UPDATE: I have tested the array length after a delay, it is being populated after all the ajax requests have been completed yet I need other requests to wait for this request to finish so that the other requests will use updated data. This request is in another ajax success so keep that in mind.

KeDeN
  • 105
  • 11

2 Answers2

0

If you want do other ajax on completion you can call your next ajax call on done function of previous ajax.

$.ajax({ ... }).done(second_ajax_fn);

Also you can set async:false but it is not recommended

melvin
  • 2,571
  • 1
  • 14
  • 37
0

The issue is likely that you're checking the value of trashData before the actual async requests are complete. If you want to ensure that all the requests are complete and then check it (or make more requests), you need something like jQuery Deferred - waiting for multiple AJAX requests to finish.

sushain97
  • 2,752
  • 1
  • 25
  • 36