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?