In my code below I am using javascript and php for building registration form. There are two files register.php that contains html code for form, javascript library and javascript code. Second file reghand.php handles php code for validation and inserting data. Data is inserted correctly into database after form validation but problem appears when validation fails. It's like no javascript comes into action, when validation fails I get redirected to reghand.php where validation errors are shown {"username":"inuse","password":"missmatch"} these are errors from my reghand.php but I want to use javascript error message that's on register.php and that too should appear on the form page itself, I was never supposed to redirect to reghand.php. Please help.

register.php

<script type="text/javascript" src="./js/jquery.min.js"></script>
       <script>
        $(document).ready(function(){
  $("form.register").change(function() {
    $.post("register.php", $("form.register").serialize(), function( data ) {
      if( data.flname == "cntbempty" )
        $("p#name_error").slideDown();
      else
        $("p#name_error").hide();
      if( data.username == "inuse" )
        $("p#username_error").slideDown();
      else
        $("p#username_error").hide();
      if( data.password == "missmatch" )
        $("p#password_error").slideDown();
      else
        $("p#password_error").hide();
      if( data.email == "notvalid" )
        $("p#email_error").slideDown();
      else
        $("p#email_error").hide();
    }, "json");
  });
});
</script>
   <form action="reghand.php" method="post" class="register">
   <fieldset>
   <legend>Registration</legend>
   <input type="text" name="fname" required="required" maxlength="15" placeholder="First Name"/>        
   <input type="text" name="lname" required="required" maxlength="15" placeholder="Last Name"/>
   <p id="name_error" class="error">First name Last name cannot be empty and can be same</p>
   <input type="text" name="username" required="required" maxlength="15" placeholder="Username" class="username" />        
   <p id="username_error" class="error">That Username is unavailable</p>       
   <input type="email" name="email" required="required" maxlength="35" placeholder="Email"/>        
   <p id="email_error" class="error">That Email is already registered</p>       
   <input type="password" name="password" required="required" maxlength="15" placeholder="Password"/>        
   <input type="password" name="password2" required="required" maxlength="15" placeholder="Confirm Password"/>
   <p id="password_error" class="error">Passwords do not match</p>
   <input type="submit" name="reg" value="Sign Up!">
 </fieldset>
</form>

reghand.php

<?php
if(isset($_POST['reg'])){
 $fn = ucfirst($_POST['fname']);
 $ln = ucfirst($_POST['lname']);
 $un = $_POST['username'];
 $em = $_POST['email'];
 $pswd = $_POST['password'];
 $pswd2 = $_POST['password2'];

 $sql=$db->prepare("SELECT username FROM users WHERE username=:username");
 $sql->execute(array(':username'=>$un));
 $row = $sql->fetch(PDO::FETCH_ASSOC);
 $db_username = $row['username'];
 $usernames = $db_username;

 $data = array();
 if( isset($fn) && isset($ln) ) {
  if( $fn != "" && $ln!="" && $fn == $ln ) {
    $data["flname"] = "cntbempty";
   }
  }
 if( isset($un) ) {
  if ($un == $usernames )  {
    $data["username"] = "inuse";
   }
  }
 if( isset($pswd) && isset($pswd2) ) {
  if( $pswd2 != "" && $pswd != $pswd2 ) {
    $data["password"] = "missmatch";
   }
  }
  if( isset( $em ) ) {
   if( $em != "" && !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST["email"] ) ) {
     $data["email"] = "notvalid";
   }
  }
 if(!empty($data))
 {
 echo json_encode($data);
 die;
 }
  else{

  $pswd = password_hash($pswd, PASSWORD_DEFAULT);
  $pswd2 = password_hash($pswd2, PASSWORD_DEFAULT);
  $stmt = $db->prepare("INSERT INTO users (username,first_name,last_name,email,password,password2,) VALUES (:username,:first_name,:last_name,:email,:password,:password2,)");  
  $stmt->execute( array(':username'=>$un,':first_name'=>$fn,':last_name'=>$ln,':email'=>$em,':password'=>$pswd,':password2'=>$pswd2));
  }
  if ($stmt->rowCount() == 1) {
    header("Location: login.php");
  } 
  else {
    echo "error";
  }
}
?>

I am not going to talk about your script in detail for now because you need to understand how form tag works in HTML.

If you use input tag as type="submit" for a form without using onsubmit event handler in the form tag, you WILL always go to the page which is specified in action property of the form tag regardless your attempt to put any javascript in the page. Besides; your current validation is done WHEN the page is loaded, not when a form is submitted. Nothing more. That said, you could fix this in 2 ways.

One way is to call a javascript form validation in your form tag, such as <form action="..." ... onsubmit="validateThisForm(this)">. You would need to wrap around your current script inside a function named validateThisForm(formObj) (must be corresponding to the function named being called in the form tag), and remove $(document).ready part because it has nothing to do with the script.

Another way is to implement redirect to a correct page inside your reghand.php file. This way would require some updates on your current HTML as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.