Ajax takes time to complete. The execution of the function does not take much time. Thus, by the time you get your warning outside of the ajax request, the ajax request is still using the time to complete (either in the transfer or in the server-side actions).
You can always wait for the ajax method to 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 call back.
$(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 });
source share