0

Has anyone found that their javascript doesnt work, but when they step through the code it works fine ?

    var cookie = getCookie('lusr');
var username = cookie;
if(!cookie){
    $("#UserNav").load("loginform.html");
    $("#loginbtn").click( function(){
        var username = $("#usernametxt").val();
        var password = $("#passwordtxt").val();
        login(username,password);
    });
}else{
    $("#UserNav").load("user.htm");
    $("#WelcomeUser").text("Welcome "+ username);
}

My issue occurs on this line :

        $("#WelcomeUser").text("Welcome "+ username);
Rndm
  • 6,710
  • 7
  • 39
  • 58
Billybonks
  • 1,568
  • 3
  • 15
  • 32

2 Answers2

1

You are using the load() function which asynchronously fetches from the server. This means your form has not loaded by the time you go searching for its fields.

The reason it works when you step through is because it gives it time to load the form while you step.

You can use another version of load which has an asynchonous callback function, allowing you to provide functionality only to be called once the load is complete.

Check the jQuery docs for more info.

Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
1

That's because load() is asynchronous: it returns right away, performs its work in the background, then calls a user-provided function when its task is complete. The stepping delay gives you the illusion that the function is synchronous and performs all its work before returning.

Therefore, you should pass a callback function to load() and perform your subsequent work inside that callback:

var cookie = getCookie("lusr");
if(!cookie) {
    $("#UserNav").load("loginform.html", function() {
        $("#loginbtn").click(function() {
            var username = $("#usernametxt").val();
            var password = $("#passwordtxt").val();
            login(username, password);
        });
    });
} else {
    $("#UserNav").load("user.htm", function() {
        $("#WelcomeUser").text("Welcome " + cookie);
    });
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479