title: Email validation using JQuery Ajax
body: <p>I've been having a hard time trying to validate an email with ajax
  using PHP and Javascript. What I want to do, is to check if the email
  already exists in the database, if so, display a message and then go
  back to the form, otherwise display a success message and close the
  form. The problem is that if the email exists it is displaying the
  "error message" and then displays the success message. I've checked
  similar questions and tried the code in them but none of them applied
  correctly to my requirements. Thank you.</p>
  
  <p>Here's what I've got:</p>
  
  <pre><code>// JavaScript Document
  $('#btnSubmit').click(function(){
      if(  validateForm() ){
          // code to submit all the info, display the success message and close the form
      }
      else return false;
  });
  
  
  // I created a function to validate all the fields in the form
  function validateForm() {
      var firstName = $('#txtFirstName').val();
      var lastName = $('#txtLastName').val();
      var email = $('#txtMail').val();
  
      // to validate firstName and lastName I do it like this:
      if(!firstName || firstName.length === 0) {
          message = "All fields are mandatory\\nFirst Name is required";
          messageDialog("Warning", message, "warning", 2);
          return false;
      } 
      if( !firstName.match(letters) ) {
          message = "Invalid name";
          messageDialog("Warning", message, "warning", 2);
          return false;
      }
      // So far, no problem at all. But when I tried to validate email:
      else {
          // use ajax to check if a user has been previously registered
          // using this email
          $.ajax({
              url:"check_user.php",   // url that will use
              data:{                  // data that will be sent
                  email:email
              },
              type:"POST",            // type of submision
              dataType:"text",        // what type of data we'll get back
              success:function(data)
              {    
                  // if check_user returns a number different than 0
                  // means that there's already a user registered with that email
                  if(data &gt; 0 ) {
                      message = "This email is registered already!";
                      messageDialog("Error", message, "error", 2);
                      return false;                   
                   }
                   else { return true;}
              }
          });
  
      }
  
      // if everything is right then return true so the submit function continue its execution
      return true;
  }
  </code></pre>