Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting local variable in a JavaScript callback function

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.

like image 321
Alex Avatar asked Feb 20 '12 21:02

Alex


People also ask

Can I make a local variable global JavaScript?

You can copy a local variable to the global scope by doing window. myVar = myVar (replacing window by whatever is your global object), but if you reassign the local one, the global copy won't follow.

Can I return value from callback function JavaScript?

When a callback function completes execution, it returns any return value that it might have to the DataBlade API, which invoked it.


2 Answers

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 sees array as undefined because success hasn't run yet. In order to make this work you need to delay the console.log call until after success completes.

$(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();
    }});
});
like image 59
JaredPar Avatar answered Oct 29 '22 19:10

JaredPar


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.

like image 41
GoldenNewby Avatar answered Oct 29 '22 19:10

GoldenNewby