0

So here is my code:

$.ajax({
    url: "src/logcheck.php",
    type: "POST",
    dataType: "JSON",
    async: true,
    data: {cookie: logCookieHashed},
    success: function(json){
        loggedUser = json.user;
        alert(loggedUser);
    }
});
delay(500);
alert(loggedUser);

When I call "alert(loggedUser)" for first time the output is correct, but when I call it for second time it outputs empty string, loggedUser is global variable.

  • It's because the request is asynchronous. `alert(loggedUser)` is being hit before the request completes. Using a delay function is not a great idea - what happens if the response takes 501ms to come back? The question I linked to contains a full description of the issue and the best practices in this situation. – Rory McCrossan Feb 20 '15 at 16:02
  • @RoryMcCrossan fixed the problem by moving the code after the delay() function inside the success body – Hristo Temelski Feb 21 '15 at 11:26

0 Answers0