title: form validation with red error messages not working (php, ajax, jquery, and mysql)
body: <p>Well, brothers, I'm having a problem with the appearance of notices concerning the form validation. I associate the problem to a few issues on the php code like arrays defined by the variables $errors and $data. I really didn't understand the usage of them. Or maybe it's related to somewhere in the jQuery code.<br>
  These codes were based on a website tutorial I've found on the internet. Also, I have no experience in the Ajax and jQuery arenas. Maybe you can solve this simple issue. I even appended the screen captures of the sign up page along with the next page which processes the php connection with database.</p>
  
  <p><a href="http://i.stack.imgur.com/r93rM.png" rel="nofollow">This is the sign up page called join_form.php</a></p>
  
  <p><a href="http://i.stack.imgur.com/mIarG.png" rel="nofollow">This is the processing page called register2.php</a></p>
  
  <p>This is html code:</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
     &lt;title&gt;
      This is the form page
    &lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;center&gt;
        &lt;br&gt;
        &lt;br&gt;
        &lt;img src="images/quintz.png" width="156" height="44" alt=""/&gt;
        &lt;br&gt;
        &lt;br&gt;
        Register now
        &lt;br&gt;
        &lt;br&gt;
        &lt;div id="bugado"&gt;
          &lt;form id="ajax_form" method="post" action="register2.php"&gt;
            &lt;div id="usertype-group" class="form-group"&gt;
              &lt;label for="usertype"&gt;
                You're a 
                &lt;/label&gt;
  
                &lt;select name="usertype" class="form-control"&gt;
                  &lt;option value="native speaker"&gt;
                    Native speaker
                  &lt;/option&gt;
                  &lt;option value="non-native speaker"&gt;
                    Non-native speaker
                  &lt;/option&gt;
                &lt;/select&gt;
                &lt;br&gt;
                &lt;!-- errors will go here --&gt;
                &lt;/div&gt;
                &lt;div id="username-group" class="form-group"&gt;
                  &lt;label for="username"&gt;
                    Create username: 
                  &lt;/label&gt;
  
                  &lt;input name="username" type="text" maxlength="30" class="form-control" placeholder="Username"&gt;
                  &lt;br&gt;
                &lt;/div&gt;
                &lt;div id="email-group" class="form-group"&gt;
                  &lt;label for="email"&gt;
                    Email: 
                  &lt;/label&gt;
  
                  &lt;input name="email" type="text" maxlength="50" class="form-control" placeholder="Email"&gt;
                  &lt;br&gt;
                  &lt;!-- errors will go here --&gt;
                &lt;/div&gt;
                &lt;div id="password-group" class="form-group"&gt;
                  &lt;label for="password"&gt;
                    Create password: 
                  &lt;/label&gt;
  
                  &lt;input type="password" name="password" class="form-control" placeholder="Password"&gt;
                  &lt;br&gt;
                &lt;/div&gt;
                &lt;label&gt;
                  Confirm password: 
                &lt;/label&gt;
  
                &lt;input type="password" name="confirm_password" class="form-control" placeholder="Password again"&gt;
                &lt;br&gt;
                &lt;button type="submit" name="submit" class="btn btn-success"&gt;
                  Submit
                &lt;/button&gt;
                &lt;span class="fa fa-arrow-right"&gt;
                &lt;/span&gt;
                &lt;br&gt;
                &lt;input name="reset" type="reset" value="Reset"&gt;
                &lt;/form&gt;
                &lt;/div&gt;
            &lt;/center&gt;
        &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>This is the jQuery code:</p>
  
  <pre><code> &lt;script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"&gt;&lt;/script&gt;
   &lt;script language="javascript"&gt;
      $(document).ready(function() {
  
      // process the form
      $('#ajax_form').submit(function(event) {
  
          $('.form-group').removeClass('has-error'); // remove the error class
          $('.help-block').remove(); // remove the error text
  
          // get the form data
          // there are many ways to get this data using jQuery (you can use the class or id also)
          var formData = {
              'usertype'               : $('select[name="usertype"]').val(),
              'username'              : $('input[name="username"]').val(),
              'email'             : $('input[name="email"]').val(),
              'password'  : $('input[name="password"]').val()
          };
  
          // process the form
          $.ajax({
              type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
              url         : $(form).attr('action'), // the url where we want to POST
              data        : formData, // our data object
              dataType    : 'json', // what type of data do we expect back from the server
              encode      : true
          })
              // using the done promise callback
              .done(function(data) {
  
                  // log data to the console so we can see
                  console.log(data); 
  
                  // here we will handle errors and validation messages
                  if ( ! data.success) {
  
                      // handle errors for usertype ---------------
                      if (data.errors.usertype) {
                          $('#usertype-group').addClass('has-error'); // add the error class to show red select
                          $('#usertype-group').append('&lt;div class="help-block"&gt;' + data.errors.usertype + '&lt;/div&gt;'); // add the actual error message under our select
                      }
  
                      // handle errors for username ---------------
                      if (data.errors.username) {
                          $('#username-group').addClass('has-error'); // add the error class to show red input
                          $('#username-group').append('&lt;div class="help-block"&gt;' + data.errors.username + '&lt;/div&gt;'); // add the actual error message under our input
                      }
  
                      // handle errors for email ---------------
                      if (data.errors.email) {
                          $('#email-group').addClass('has-error'); // add the error class to show red input
                          $('#email-group').append('&lt;div class="help-block"&gt;' + data.errors.email + '&lt;/div&gt;'); // add the actual error message under our input
                      }
  
                      // handle errors for superhero alias ---------------
                      if (data.errors.password) {
                          $('#password-group').addClass('has-error'); // add the error class to show red input
                          $('#password-group').append('&lt;div class="help-block"&gt;' + data.errors.password + '&lt;/div&gt;'); // add the actual error message under our input
                      }
  
                  } else {
  
                      // ALL GOOD! just show the success message!
                      $('#ajax_form').append('&lt;div class="alert alert-success"&gt;' + data.message + '&lt;/div&gt;');
  
                      // usually after form submission, you'll want to redirect
              // window.location = '/thank-you'; // redirect a user to another page
              alert('success'); // for now we'll just alert the user
  
                  }
              })
  
              // using the fail promise callback
              .fail(function(data) {
  
                  // show any errors
                  // best to remove for production
                  console.log(data);
              });
  
          // stop the form from submitting the normal way and refreshing the page
          event.preventDefault();
      });
  
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>And this is the php code:</p>
  
  <pre><code>    &lt;?php
      include 'db.php';
  
       $errors         = array();      // array to hold validation errors
       $data           = array();      // array to pass back data
  
       //Searching for identical usernames
       $search = mysql_query("SELECT * FROM natspeaker WHERE username = '".$_POST['username']."'");
       $count = mysql_num_rows($search);
  
       $search2 = mysql_query("SELECT * FROM nonnatspeaker WHERE username = '".$_POST['username']."'");
       $count2 = mysql_num_rows($search2);
  
       //Searching for identical emails
       $search3 = mysql_query("SELECT * FROM natspeaker WHERE email = '".$_POST['email']."'");
       $count3 = mysql_num_rows($search3);
  
       $search4 = mysql_query("SELECT * FROM nonnatspeaker WHERE email = '".$_POST['email']."'");
       $count4 = mysql_num_rows($search4);
  
       //if( isset( $_SERVER['REQUEST_METHOD'] ) &amp;&amp; $_SERVER['REQUEST_METHOD']=='POST' ) {
       if(isset($_POST)){
       //USERTYPE
       if(empty($_POST['usertype'])) { 
          $errors['usertype'] = "Please select if you are a native or a non-native speaker.&lt;br&gt;";
              }
  
       //USERNAME
       if (empty($_POST['username'])) {
          $errors['username'] = "Username is missing&lt;br&gt;";
              }else{//this "else" can be deleted
  
       /*this can be deleted in case of trouble*/if ( $count == 1 OR $count2 == 1) {
          $errors['username'] .= "Username already exists in our database. Choose another one&lt;br&gt;";
              }
              }//this bracket can be deleted.
       //EMAIL
       if (empty($_POST['email'])) {
          $errors['email'] = "Email is missing&lt;br&gt;";
              }else{//this "else" can be deleted
  
        if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $_POST['email'])) {
          $errors['email'] = "Invalid email&lt;br&gt;";
              }
  
         if ( $count3 == 1 OR $count4 == 1) {
          $errors['email'] = "Email already exists in our database. It seems you have an account yet.&lt;br&gt;";
              }
              }//this bracket can be deleted.
  
        //PASSWORD
        if (empty($_POST['password'])) {
          $errors['password'] = "Password is missing.&lt;br&gt;";
              }else{//this "else" can be deleted
  
        if (strlen($_POST['password']) &lt; 6) {
          $errors['password'] = "Password too short&lt;br&gt;";
              }
              }//this bracket can be deleted.
  
  
          // return a response ===========================================================
  
         // if there are any errors in our errors array, return a success boolean of false
        if ( ! empty($errors)) {
  
          // if there are items in our errors array, return those errors
          $data['success'] = false;
          $data['errors']  = $errors; 
          //if(count($_SESSION['errors']) &gt; 0){
          //This is for ajax requests:
          if( isset( $_SERVER['REQUEST_METHOD'] ) &amp;&amp; $_SERVER['REQUEST_METHOD']=='POST' ) {
              //if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp;  strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])== 'xmlhttprequest') {//something is wrong with this
                  header('Content-type: application/json');
                  echo "Ajax request is working.";
                  echo json_encode($data);//now this iss working
                  exit;
               }
             //This is when Javascript is turned off:
             echo "&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;center&gt;&lt;div style=\"font-size:50;\"&gt;something is wrong or your Javascript is turned off. Ajax request is not working&lt;/div&gt;&lt;/center&gt;&lt;br&gt;&lt;br&gt;";//delete
             echo $data;//delete
             //foreach($_SESSION['errors'] as $key =&gt; $value){
            //echo "&lt;li&gt;" . $value . "&lt;/li&gt;";
             //}
             //echo "&lt;/ul&gt;";exit;
      }else{
      // if there are no errors process our form, then return a message
  
          // DO ALL YOUR FORM PROCESSING HERE
          // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
  if ( $_POST['usertype'] == "native speaker") { 
        $register = mysql_query("INSERT INTO natspeaker(username, email, password, time1, usertype)
         VALUES ('".$_POST['username']."','".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
          }elseif ( $_POST['usertype'] == "non-native speaker"){
           $register = mysql_query("INSERT INTO nonnatspeaker(username, email, password, time1, usertype)
          VALUES ('".$_POST['username']."', '".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
           }
  
        // Let's mail the user!
        $subject = "Your Membership at Quintz!";
        $message = "Hi, ".$_POST['username'].",
        Thank you for registering at our website, http://www.quintz.club!
  
        You have registered as a ".$_POST['usertype'].".
        You are two steps away from logging in and accessing our exclusive members area.
  
        To activate your membership, please click here: http://www.quintz.club/activate.php
  
        Once you activate your membership, you will be able to login.
  
        And please do not forget to complete your profile.
        Thanks!
        The Webmaster
  
        This is an automated response, please do not reply!";
  
        mail($_POST['email'], $subject, $message, "From: Quintz Webmaster&lt;support@quintz.club&gt;\nX-Mailer: PHP/" . phpversion());
  
        // show a message of success and provide a true success variable
          $data['success'] = true;
          $data['message'] = 'Your account has been created successfully. Go to your email address and activate your account.';
          echo "successful register!";//delete
     }
  }
  //}
  // return all our data to an AJAX call
  //this works
  //echo json_encode($data);//delete
  ?&gt;
  </code></pre>
  
  <p>In sum, I just want to hinder the user from registering with a username that already exists in the database, or with an invalid email, or even missing information (blank fields), and just return those red notices in the same page join_form.php. The user can only go to the register2.php, if all information are approved to be passed to the database and finally exhibits the message "Successful register!" on this page and sends an email to the user. Just that!</p>