1

I'm new in Javascript and only have a little knowledge about callback and how asynchronous program works. I'm trying to fill an array from the result of PHP post but in the end the array is empty.

showModalLink = function(d, i) {
$('#myModalLabel').text(d.source.name + ' - ' + d.target.name);
$('#modalJum').text(d.jumlahlelangsama);
var lelang = d.daftarlelangsama.split(", ");
var lelangmodal = [];
for (var i = 0; i < lelang.length; i++) {
   querystring = "select pemenang from lelang where id = " + lelang[i];
   console.log(querystring);
    var queryobj = {
        query: querystring
    };
    $.post('indikasi3modal.php', queryobj, function(result) {
      console.log(result);
      if (result == d.source.name) {
        lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.source.name);
      }
      else if (result == d.target.name) {
        lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.target.name);
      }
      else {
        lelangmodal.push(lelang[i]);
      }
    });  
}
$('#modalLelang').text(lelangmodal);
$('#myModal').modal('show');}

I'm wondering why the array is still empty after pushing the result. Any help appreciated. Thanks!

Dolorosa
  • 573
  • 3
  • 10
  • 29
  • As you mentioned, the `post` method is executed asynchronically executed. That means that the code after it might run before it actually completes. – MorKadosh Sep 18 '16 at 09:02
  • @MorKadosh Yes Sir, but i have no idea how to complete the `post` method before it calls another function... – Dolorosa Sep 18 '16 at 09:07
  • A number of choices. The easiest one to try is to update the list and the UI inside your callback method that executes on the result of post. But for the larger applications that will probably be bad for the overall application structure. So you might read something about Promises [link](http://www.html5rocks.com/en/tutorials/es6/promises/). Or look into using some framework like angularJS. – Vladimir M Sep 18 '16 at 09:11
  • @VladimirM Thank you for your suggestion, Sir. I tried promise for the first time and still trying to make it work [here](http://stackoverflow.com/questions/39556665/javascript-using-promise-for-post-php-get-undefined-result). Still a long way to go, perhaps... – Dolorosa Sep 18 '16 at 10:34

0 Answers0