Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly do I write a callback function to change a global variable inside AJAX for jquery?

Okay, so I look around a lot of answers and none of them seems helpful in what I want to achieve. Say I have the following code:

var n = 0;
$.ajax({
    ...
    success: function(data){
        n = Math.floor((Math.random()*10) + 1);
        somefunction(n);
    }
});

console.log(n) // n would obviously be 0 again

I had done it by making it synchronous using async:false, but from what I read, it's bad for the user experience as it freezes up the browser as it waits for result. how exactly do I implement the callback function in the above case to allow global variable n to be modified after ajax call?

like image 562
Bango Avatar asked Nov 07 '15 07:11

Bango


1 Answers

Async functions are executed in a different thread (non-blocking) thus the callback will be called past your next instruction:

console.log(n);

n is set after the callback (success function) is called but the log is before the async function is done. An easy solution is to wrap your code in a function and call it after jQuery calls success function. Note that you won't need to reference the global variable as it will be set outside of the jQuery scope and accessible to operation_x function scope.

var n = 0;
function operation_x(){
    console.log(n); // n is set to random value
}
$.ajax({
    ...
    success: function(data){
        n = Math.floor((Math.random()*10) + 1);
        somefunction(n);
        operation_x();
    }
});
console.log(n); // n is 0
like image 96
Schahriar SaffarShargh Avatar answered Oct 23 '22 08:10

Schahriar SaffarShargh