Setting a local variable in a JavaScript callback function

I'm relatively new to JavaScript, and I thought I knew how callback functions work, but after a couple of hours of searching the Internet, I still don't understand why my code is not working.

I am making an AJAX request that returns an array of strings. I am trying to set this array to a local variable, but it seems to lose its value as soon as the callback function is executed.

var array; $.ajax({ type: 'GET', url: 'include/load_array.php', dataType: 'json', success: function(data){ array = data; }, error: function(jqXHR, textStatus, errorThrown){ alert("Error loading the data"); } }); console.debug(array); 

In the console, array displayed as undefined. Can someone explain to me why this is not set and how to set a local variable in the callback function.

+6
source share
5 answers

The problem is that console.log is running synchronously, and the ajax call is running asynchronously. Therefore, it starts before the callback completes, so it still sees the array as undefined , because success is not running yet. To do this, you need to delay the console.log call until success completed.

 $(document).ready(function() { var array; var runLog = function() { console.log(array); }; $.ajax({ type: 'GET', url: 'include/load_array.php', dataType: 'json', success: function(data){ array = data; runlog(); }}); }); 
+7
source

The first A in ajax is for Asynchronous, which means that by the time you debug the array, the result was still not delivered. The array is undefined at the display point of its value. You need to do console.debug below array = data.

+2
source

The success function is not executed immediately, but only after receiving an HTTP response. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP response data, do this from within the success function, or alternatively define this operation inside the function, and then call this function from the success callback.

+1
source

Try calling a function to set this variable after success :

 var array; var goodToProceed = function(myArr) { console.debug(myArr); }; $.ajax({ type: 'GET', url: 'include/load_array.php', dataType: 'json', success: function(data){ goodToProceed(data); }, error: function(jqXHR, textStatus, errorThrown){ alert("Error loading the data"); } }); 
+1
source

AJAX is asynchronous. You set the variable array , but only after that does debug execute. Making an AJAX call sends a request, but then continues in code. At some later point, the request returns and your success or error functions are executed.

0
source

Source: https://habr.com/ru/post/908929/


All Articles