Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .ajax() local variable can't assign to global

I have a jquery ajax code as following:

$(document).ready(function() {
  var global_arr = new Array();
  $.ajax({
    url: 'result.php',
    type: 'post',
    dataType: 'json',
    success: function(data) {
       $.each(data, function(key, value) {
          global_arr.push(value.name);
       });
       alert(global_arr); //get correct value, works fine
     }
  }); //end of ajax function
  alert(global_arr); //get null, it doesn't work properly
});

Notice the lines to alert global_arr, why I can't get the value out of $.ajax() function? Thanks anyone help on this.

like image 555
user2241859 Avatar asked Apr 03 '13 19:04

user2241859


3 Answers

Ajax takes time to complete. The function execution does not take nearly as much time. So by the time you get to your alert outside of the ajax request, the ajax request is still using time to complete (either in transmission or in server side actions).

You can always wait for the ajax method to be complete.

$(document).ready(function() {

 var global_arr = new Array();
 var complete = false;//flag to wait for ajax completion
 $.ajax({
  url: 'result.php',
  type: 'post',
  dataType: 'json',
  success: function(data) {
   $.each(data, function(key, value) {
      global_arr.push(value.name);
   });
   alert(global_arr); //get correct value, works fine
   complete = true;//mark ajax as complete
  }
 }); //end of ajax function

 (function runOnComplete(){
  if( complete ){//run when ajax completes and flag is true
   alert(global_arr);
  }else{
   setTimeout(runOnComplete,25);//when ajax is not complete then loop
  }
 })()
});

However, the most common way is to use a callback.

$(document).ready(function() {

 function runOnComplete(){//code executes once ajax request is successful
  alert(global_arr);
 }
 var global_arr = new Array();
 $.ajax({
  url: 'result.php',
  type: 'post',
  dataType: 'json',
  success: function(data) {
   $.each(data, function(key, value) {
    global_arr.push(value.name);
   });
   alert(global_arr); //get correct value, works fine
   runOnComplete();//callback
  }
 }); //end of ajax function
});
like image 128
Travis J Avatar answered Oct 17 '22 04:10

Travis J


Ajax is asynchronous. At the time the JS engine reaches your non-functioning alert() line, the AJAX call has not yet had a chance to get a response from the server and set the variable.

That's why the inner alert() works. It gets executed when the response comes in from the server.

like image 5
Marc B Avatar answered Oct 17 '22 04:10

Marc B


Ajax function runs asynchronously and before ajax function adds incoming data in your array, the outer alert function runs and for this reason alerts an empty array.

You can use async-await to make the outer alert function wait for the incoming data.

  $(document).ready(async function() {
      var global_arr = new Array();
      await $.ajax({
        url: 'result.php',
        type: 'post',
        dataType: 'json',
        success: function(data) {
           $.each(data, function(key, value) {
              global_arr.push(value.name);
           });
           alert(global_arr);
        }
      }); //end of ajax function
      alert(global_arr); //it will work fine now
  });
like image 1
Husokanus Avatar answered Oct 17 '22 03:10

Husokanus