开发者

jquery - javascript variable not holding value

开发者 https://www.devze.com 2022-12-14 06:30 出处:网络
I\'m using this code to submit a form to a php script: var valid = \'true\'; $(document).ready(function(){

I'm using this code to submit a form to a php script:

var valid = 'true';
$(document).ready(function(){
  $("#contact").submit(function(){
    $.post("process.php",
      $("#contact").serialize(),
      function(data){
        if(data.email_check ==开发者_运维问答 'invalid'){
          valid = 'false'; //<---not set!
          $("#email1").addClass('missing'); 
          $("#message_ajax")
            .html("<div class='errorMessage'>Sorry is NOT a valid e-mail address. Try again.</div>");
        } else {
          $("#message_ajax")
            .html("<div class='errorMessage'>YES! this is A valid e-mail address. DO NOT Try again.</div>");
        }
      }, "json"
    );

    if(valid == 'true'){
      $("#contact").hide();
    }

    return false;
  });
});

I know the script is returning the 'invalid' value because the div and css are updated as expected, but the 'valid' variable never gets set to 'false'. Thinking it was a scope issue I have moved the declaration and if statement around with no joy.

Possible related problem - I'm using firebug to step through the code, but it only stops at my breakpoint the first time the code is executed, and never again, but I can submit the form any number of times and it always responds as expected - valid or invalid. As you can see, I'm very new to jQuery.


You're mixing synchronous and asynchronous code here.

if(valid == 'true'){
    $("#contact").hide();
}       

return false;

This code ^^^ runs before the callback function(data) is ever called.

Basically what's happening is this:

  • $.post runs
  • if(valid == 'true') is evaluated
  • .submit() function returns false
  • The callback function(data) is called
  • 'valid' variable is set
0

精彩评论

暂无评论...
验证码 换一张
取 消