views:

80

answers:

1

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.

+5  A: 

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
T. Stone
+1 thanks. So if I understand, I need to put the logic that hides the form in the function(data) block? Eventually I will have several inputs to validate and I only want to hide the form if all pass.
jriggs
@jriggs -- Yes, exactly. Keep in mind there will be a delay between the $.post and the function(data), so you might also want to add a little message asking the user to wait, and then hide that after the callback is fired.
T. Stone