8

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.

5 Answers 5

8

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();
    }});
});
Sign up to request clarification or add additional context in comments.

3 Comments

I think you're confused by the formatting of the code. The console.debug is directly after the ajax.
I believe the scoping is correct, it's just the formatting is off for the first two non-blank lines (they should be shifted left 1).
@JamesMontagne you're exactly correct. The formatting really threw me off. Updated the answer.
2

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.

3 Comments

Ah ha, it seems so obvious now! Is there an alternative to AJAX that you would recommend to guarantee that the program waits for the response before it continues execution?
You can do synchronous http calls in javascript, but there's no reason you should want to do it. Just start working with the result in the right scope next time.
That's SJAX. Synchronous, i.e. the execution will be blocked until the result has been retrieved. In your request json, if you introduce async: false, then the retrieval will be synchronous - in simple words, your previous code will work. But then again, this is bad practice. Putting your debugging code inside a callback as pointed out by GoldenNewby is the way to go.
1

The success function doesn't execute immediately, but only after the HTTP-response arrives. Therefore, array is still undefined at this point. If you want to perform operations on the HTTP-response data, do it from within the success function, or alternatively, define that operation inside of a function and then invoke that function from within the success callback.

Comments

1

Try calling a function to set this variable after your 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");
}
});

3 Comments

Why bother making an anonymous function that calls goodToProceed instead of just having it get called directly upon success?
Yes GoldenNewby, good point. I do it often but indeed, no need to do it.
@adis, sometimes is good to do it, to untangle the code, however, you don't need an anonymous function in that case. just define success: goodToProceed,
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.