0

I'm building an app using jQuery mobile but I have this problem where I call a function and assign a value within that function to a global var. When I try to log the var value to the console I get null. Then when I call the function again it displays the correct value. This is the code where have the problem:

var sessionId;

function startGame() {
    getGameSession();
    console.log(sessionId);

    /*
    if (sessionId != null) {
        loadGame();
    } else {
            displayMessage("Error", "Unable to load game");
    }
    */
}

function getGameSession() {
    var gameSession;
    $.ajax({
        type: "GET",
        url: "/answerIQ/index.php/get-game-session",    
        data: {},    
        success: function (data) {
            if (data.gameStatus == "success") {    
                sessionId = data.gameSession;
            } else {    
                displayMessage("Error", data.gameMessage);    
            }    
        },
        dataType: "JSON"
    });
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
nSams Dev
  • 687
  • 2
  • 8
  • 21
  • 6
    ajax is asynchronous, use promises/deferred Objects before checking sessionId – Fabrizio Calderan Dec 23 '15 at 14:53
  • 1
    The `console.log` line actually gets executed before your `success` handler is called because of the nature of ajax. – Alen Genzić Dec 23 '15 at 14:54
  • 1
    Check out [How do I return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/1799146) to learn why your console.log shows `null` and how you may be able to make use of callbacks and or promises – julian soro Dec 23 '15 at 14:58
  • Thanks all, that link explains everything. it all works now :) – nSams Dev Dec 23 '15 at 15:05

0 Answers0