I'm relatively new to JavaScript and I thought I knew how callback functions worked but after a couple of hours of searching the web I still do not understand why my code is not working.
I am making an AJAX request which returns a string array. I'm trying to set this array to a local variable, but it seems to lose it's 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
appears as undefined. Can anyone explain to me why this is not being set and how it is possible to set a local variable in a callback function.
AJAX is asynchronous. You are setting the
array
variable, but not until after thatdebug
executes. Making an AJAX call sends a request but then continues on in the code. At some later point, the request returns and yoursuccess
orerror
functions execute.The first A in ajax is for Asynchronous, which means that by the time you are debugging the array, the result still hasn't been delivered. Array is undefined at the point of displaying it's value. You need to do the console.debug below array = data.
The problem here is that
console.log
executes synchronously while the ajax call executes asynchronously. Hence it runs before the callback completes so it still seesarray
asundefined
becausesuccess
hasn't run yet. In order to make this work you need to delay theconsole.log
call until aftersuccess
completes.Try calling a function to set this variable after your
success
:The
success
function doesn't execute immediately, but only after the HTTP-response arrives. Therefore,array
is stillundefined
at this point. If you want to perform operations on the HTTP-response data, do it from within thesuccess
function, or alternatively, define that operation inside of a function and then invoke that function from within thesuccess
callback.