简体   繁体   中英

jquery - javascript variable not holding value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM