0

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

3
  • is it because the flow of control moves onto the next function before $.post() can respond ? Commented Jul 24, 2011 at 5:22
  • There is a space before " Username already exists...". Is that a mistake? Commented Jul 24, 2011 at 5:23
  • @danialentzry : No that was intentional. And the issue was timme lag. Thanks anyways :D Commented Jul 24, 2011 at 5:24

2 Answers 2

1

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");
        }
     });
Sign up to request clarification or add additional context in comments.

1 Comment

tried that, doesn't work, However, the time lag issue , when corrected, seemed to make it work. Thanks anyways
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.