Hormigas
Hormigas

Reputation: 1449

JavaScript variable scope

Here's my code

errors=0;
$(document).ready(function () {
    var chk=$("#usnm").val();
    $.post("register.php",{'chkuser':chk},function(data){
        if(data==" Username already exists.Choose a new one"){
            errors++;
            alert(errors);
            $("#alerts").html(data);
        }
     });
     if(errors==0){
         alert(errors+"post");
     }
});

Here, the first alert gives me a "1" whereas the second alert runs, so therefore it give me '0post' . What i'd like to know is: How is the value of the variable errors, changing to 0 all of a sudden after being 1 ?

Thanks

Upvotes: 0

Views: 112

Answers (2)

SeanCannon
SeanCannon

Reputation: 77956

Change errors=0; to var errors=0;

and put the error check inside the $.post function:

   $.post("register.php",{'chkuser':chk},function(data){
        if(data==" Username already exists.Choose a new one"){
            errors++;
            alert(errors);
            $("#alerts").html(data);
        }
        if(errors==0){
            alert(errors+"post");
        }
     });

Upvotes: 1

Parv Sharma
Parv Sharma

Reputation: 12705

jquery.post is called asynchronously. you might be debugging it locally otherwise the second alert would go on the first place. anyways because it runs async the value is different inside and outside the post function

Upvotes: 0

Related Questions