Global variable is not being assigned within an AJAX function

Asked

Viewed 131 times

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

inserir a descrição da imagem aqui

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 to mesaPrint.

  • 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

  • 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.

1 answer

0

I’m not going in deep, but what’s happening here is an asyncronism. Note that in your AJAX you declare a callback function in the property success. Why do you need to declare a function instead of simply continuing to write your code normally? Because this function does not run immediately, it is a block of code that will run when your AJAX ends.

Your code runs on that orderm:

// 1 - variável mesasPrint é inicializada
var mesasPrint;

// 2 - função AJAX é invocada
$.ajax({
    url: BASE_URL + 'mesas/get_mesas_ajax',
    success: function(result){
        // 4 - função de callback é executada eventualmente quando o AJAX finalizar
        mesasPrint = result;
        console.log(mesasPrint);
    }

});

// 3 - mesasPrint é printado no console
console.log(mesasPrint);

This occurs to prevent other parts of the code from being locked while the code waits for the execution of a time-consuming I/O operation. Javascript does not wait for AJAX, or other I/O operations, to finish running the next line of code. If your code needs the AJAX response to continue, declare that part of the code within the callback function.

You can delve into other ways of treating asymchronism with Promises and/or await

Browser other questions tagged

You are not signed in. Login or sign up in order to post.