0
I created a global variable in Javascript and I am making an AJAX request, inside the function Success ajax, I assign the return to the global variable, but when leaving AJAX, the variable is undefined.
var mesasPrint;
$.ajax({
url: BASE_URL + 'mesas/get_mesas_ajax',
success: function(result){
mesasPrint = result;
console.log(mesasPrint);
}
});
console.log(mesasPrint);
The result is this
The ajax request is working, when I give one console.log
within the Success function it returns the JSON, however when I assign the variable mesasPrint
and try to use outside the function, is as undefined
There is a misconception in its interpretation. The global variable is not undefined when exiting AJAX, it is appearing as
undefined
on your console because you log it before AJAX completes the request, and therefore before assigning a value tomesaPrint
.– Andre
Undefined is on line 32, just past line 27. I don’t know why the log appears first, but if I leave only the console.log after ajax, still Undefined, but the console log only inside the ajax request, presents the data
– Felipe Pacheco
you need to understand that the ajax request is asynchronous, i.e., it executes in the background by releasing the following script and only after it is finished, it executes the Success function, i.e., as quickly as the request is completed, line 27 will always run after line 32. Put everything you need to do with the Int variable inside the ajax Success function.
– Jader A. Wagner