Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function on completion of another, use ajaxComplete()?

Two functions need to execute in Javascript, and one should start when another has finished.

The first populates an array with getJSON, and the second will then manipulate it.

However, getJSON is asynchronous and it will not pause the order of execution to make the program work properly so that the array finishes loading before the second function can execute.

How can one use Jquery's ajaxComplete() or else the getJSON callback to run the second function once the data has finished loading via getJSON.

Thanks.


here is the code:

function fetch_ids(user) {
  var url = 'http://test.com/ids/' + escape(user) + '.json?callback=?';
  // populate array ids[] with JSON data --uid[] array declared globally
  $.getJSON(url, function(data) {
    for (var i = 0; i < data.length; i++) ids[i] = data[i];
  });
  // test array and run alert
  for (i = 0; i < uid.length; i++) {
    for (j = 0; j < ids.length; j++) {
      if (uid[i] == ids[j]) {
        alert('matched: ' + uid[i]);
      }
    }
  }
  // finish test
}
like image 828
Adrian33 Avatar asked Mar 05 '26 06:03

Adrian33


1 Answers

Wouldn´t this work?

$.getJSON(url, params, function (jsonData){
  // populate array
  // call 2nd function.
});

Worst case, if you have your 2 funcions already defined elsewhere:

$.getJSON(url, params, function (jsonData){
  firstFunction(jsonData);
  secondFunction(jsonData);
});
like image 176
Seb Avatar answered Mar 07 '26 18:03

Seb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!