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.
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
});
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With