0

I have a function (all of the unrelated parts of been omitted) that defines a global variable window.playerLibrary. When I check window.playerLibrary in the function itself (`var check #1 I get a value. If I check it just outside of the ajax call it is undefined. If I check it after calling the function, it is undefined:

function generateAllCards() {
    $.ajax({
        type: "POST",
        url: "processGame",
        data: {
            mode: "generateCards"
        },
        dataType: "JSON",
        success: function(data) {
            window.playerLibrary = data.playerLibrary;

        // var check #1
            console.log(window.playerLibrary);
        }
    });

// var check #2
    console.log(window.playerLibrary);
}

generateAllCards();
// var check #3
    console.log(window.playerLibrary);

As I'm typing this I suspect the cause is that, since it is defined in an ajax call, var checks #2 and #3 are happening sequentially while var check #1 is happening along side of them and therefore the definition of the variable is not being captured.

If this is accurate, is there a way to fix this?

Styles2304
  • 143
  • 1
  • 14
  • 1
    What is it you want to fix? Works as intended :) – npup Nov 04 '15 at 00:25
  • This is an asynchronous issue. The 2nd and 3rd uses of the variable are not guaranteed to exist while the ajax call is occurring. – mariocatch Nov 04 '15 at 00:26
  • 1
    You are basically ordering a delivery pizza and are upset you can not eat it as soon as you hit the order button. Asynchronous calls take time to run. – epascarello Nov 04 '15 at 00:26

1 Answers1

0

Do what you need to do with the playerlibrary inside the success callback, or call a function from there once you know the value has been assigned

lucas
  • 1,485
  • 13
  • 22