Use jQuery to show errors while submitting registration form
Asked Answered
N

7

18

My last question was not clear so I am posting it with all clarification here. In the code below I want to show error messages using jQuery for registration form errors. Problem here is this code simply inserts data into database without checking any errors or showing error message and redirects to login page. So where I am going wrong?


Now I have updated my code, data is not submitted unless all conditions are fulfilled as I wanted but errors are displayed on clicking submit button, register.php page is reloaded where now it displays only error messages and no registration form like there is no use of jQuery. I don't want page to be reloaded It should show error messages right there.

<?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";
  }
}
?>

jquerycode

$(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");
  });
});
Nara answered 10/10, 2015 at 13:26 Comment(3)
You might be better off using a validation library and avoiding the hassle, .e.g jqueryvalidation.org (simple) or parsleyjs.org (a bit more advanced)Paint
You can group your isset() and $foo != '' if statements onto one line. Additionally, some of your php error checking looks weird. Your checking if values are set and if they're not empty, then you're reporting and error if that's true. Surely you only want to report the error if the values are not set or are equal to a blank string... Finally, you're not doing anything with your error checking in php to stop the database insert, what made you think it wouldn't insert into the database?Overripe
Where do you have put logic for form validation. You have to put it before $.post(0 method. But what are the if condition after form submission successful?Terrorstricken
F
8

You need to fix a few things.

  • First, the file that handles registration process should not be the same file as form.
  • It is purely for handling data so it cannot redirect the browser directly using header("Location: login.php"). This part should be handled by your javascript code.
  • You also need to tell the browser that the content being served is JSON.
  • You also need to prevent form from submitting directly

Look at the following updated code.

Create a file called: registrationHandler.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))
{
  header('Content-Type: application/json');
  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));
}
//! Send Success Status to browser for it to understand
if ($stmt->rowCount() == 1) {
  $data['success'] = true;
} 
else {
  $data['success'] = false;
}
header('Content-Type: application/json');
echo json_encode($data);
}
?>

your Javascript Code:

$(document).ready(function(){
      $("form.register").submit(function(e) {
        e.preventDefault();
        $.post("registrationHandler.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();

          if(data.success) {
            // registration succesful. Redirect
            window.location = "login.php";
          }
          else {
            // Some database error?
          }
        }, "json");
      });
    });
Fancyfree answered 13/10, 2015 at 10:53 Comment(1)
thanks your code is really good, and you explained all well, but nothing happens on submit button form remains as it is with all fields filledNara
N
5

Your problem here, as @Novocaine mentionned, is that you let the script continue after filling your $data with the errors.

For me the simple thing to do would be to init your $data as an empty array, then only fill it if there is indeed an error.

//changing the init of the $data array
$data = array();
if( isset($fn) && isset($ln) ) {
 if( $fn != "" && $ln!="" && $fn == $ln ) {
   $data["flname"] = "cntbempty";
  }
}
/* List of all your validation tests */

//Now your test if you have any errors in your $data
if(!empty($data))
{
    echo json_encode($data);
    die;
}

//And only after if the condition is not met, you can insert and redirect
/* Rest of your code here */

You will also need to add a condition to your jQuery code for checking if data.flname and the other fields are defined.

//example
if( data.flname && data.flname == "cntbempty" )
    $("p#name_error").slideDown();

I hope this helps.

Nkvd answered 13/10, 2015 at 8:45 Comment(2)
thanks it worked halfway :) but jQuery still doesn't seem to work I have updated my question will you please look at it again.Nara
If I understand correctly, your problem now is that when submitting you're sent to a page with the json reply. Correct ? If that's so, it's because you have a listener on the "change" event but not on the "submit" one. You should probably add one on the submit and redirect to login from jQuery if there is no error.Nkvd
H
5

Add header('Content-Type: application/json'); before echo json_encode($data);

$(document).ready(function(){
  $("form.register").submit(function(e) {
    e.preventDefault();
    $.post("register.php", $("form.register").serialize(), function( data ) {
      if(data.length == 0){
        window.location.href= "login.php";
      }

      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");
  });
});

Replace header("Location: login.php"); with echo(json_encode(array()))

Hoofer answered 13/10, 2015 at 10:29 Comment(1)
so it still redirects? I have updated the answer try that as well. Why to check for errors on every form changes? you can validate same on submit.Hoofer
O
4

Just re-write your code as follows and give a little try.

<?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();
     $data = 0;
   if( isset($fn) && isset($ln) ) {
    if( $fn != "" && $ln!="" && $fn == $ln ) {
      // $data["flname"] = "cntbempty";
         $data = 2;
    }
  }
  if( isset($un) ) {
    if $un == $usernames )  {
     // $data["username"] = "inuse";
        $data = 3;
}
}
if( isset($pswd) && isset($pswd2) ) {
  if( $pswd2 != "" && $pswd != $pswd2 ) {
    // $data["password"] = "missmatch";
       $data = 4;
  }
}
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";
      $data = 5;
 }
}
/* if(!empty($data))
{
  header('Content-Type: application/json');
  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));
// }
//! Send Success Status to browser for it to understand
if ($stmt->rowCount() == 1) {
  // $data['success'] = true;
     $data = 1;
} 
else {
  // $data['success'] = false;
  $data = -1;
}
// header('Content-Type: application/json');
// echo json_encode($data);

echo $data;

}
?>

and your jquery script

$(document).ready(function(){
  $("form.register").change(function() {

   var data = new FormData(this);

    $.ajax({
        type:"post",
        url: register.php,
        data:data,
        mimeType:"multipart/form-data",
        contentType: false,
        cashe: false,
        processData: false,
        error:function(data){
            alert ("An Error has Occured...");
            return false;
        },
        beforeSend: function() {
            $('#Loading').html('<img src="images/page-loader.gif" />&nbsp;&nbsp;Processing</div>');

        },
        success: function(html){
            switch($html){
                case 1:
                      alert("success");
                       window.location.href="" /* your redirect page*/;
                      break;
                      case 2:
                        $("#error").html('Field cannot be Empty !!!');
                      break;
                      case 3:
                        /* so on...*/
                      break;
                      case 4:
                      break;
                      case 5:
                      break;

            }
        }
    });
  });
});
Ordinand answered 14/10, 2015 at 8:36 Comment(0)
X
3

Do your validation of required fields on the browser before passing to the server. Then you only have to validate the username selected is not in use. And the user doesn't have to wait for the postback to get the results of the validation.

function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
        return pattern.test(emailAddress);
}

$(function(){

    $('form.register').submit(function(e){
        e.preventDefault();
        var errors = false;
        if($('#fname').val().length == 0){
            $('p#name_error').slideDown();
            errors = true;
        }else{
            $('p#name_error').slideUp();
        }

        if($('#lname').val().length == 0){
            $('p#name_error').slideDown();
            errors = true;
        }else{
            $('p#name_error').slideUp();
        }

        if($('#username').val().length == 0){
            $('p#username_error').slideDown();
            errors = true;
        }else{
            $('p#username_error').slideUp();
        }

        if(!isValidEmailAddress($('#email').val())){
            $("p#email_error").slideDown();
            errors = true;
        }else{
            $("p#email_error").hide();
        }

        if($('#password').val().length == 0){
            $("p#password_error").slideDown();
            errors = true;
        }else{
            $("p#password_error").hide();
        }

        if($('#password2').val().length == 0){
            $("p#password_error").slideDown();
            errors = true;
        }else{
            $("p#password_error").hide();
        }

        if($('#password').val() != $('#password2').val()){
            $("p#password_error").slideDown();
            errors = true;
        }else{
            $("p#password_error").hide();
        }

        if(errors){
            return;
        } 

        $.post("register.php", $("form.register").serialize(), function( data ) {
            if(data.length == 0){
                window.location.href= "login.php";
            }
            if( data == "inuse" ){
                $("p#username_error").slideDown();
            }
        }
    });
});

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 = "";
        if $un == $usernames )  {
            $data = "inuse";
        }
        if(strlen($data) == 0){
            $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));
        }
        echo data;
    }
?>
Xavier answered 19/10, 2015 at 17:31 Comment(0)
K
1

Try this

 <script>

  // When the browser is ready...
  $(function() {

    $("#your form ID").validate({

        // Specify the validation rules
        rules: {
                   fname:"required",
                   lname: "required",
                   username: "required",
                   email: "required",
                   password: "required"
            } 

 });
 $('#your form ID').submit(function(e){     
         e.preventDefault();
            var $form = $(this);
            if(! $form.valid()) return false;
         var data = $( "#your form ID" ).serialize();
            $.ajax({
            type:"POST",
            url:"",
            data:data,
            success:function(data)
            {
                   console.log(data);

            }
        });
        });
 });
</script>

For more read this tutorial http://w3code.in/2015/10/submit-a-form-with-ajax-after-jquery-validation-is-successful/

Korey answered 20/10, 2015 at 5:18 Comment(0)
R
0

.html file

please add different error field which shows error and give them id like:

#nameerr,#emailerr,,#passerr,#confirmpasserr

.css file

In this css file we give all that error id visibility hidden you can also use display if you want.

#nameerr,#emailerr,#passerr,#confirmpasserr{
     color: red;
     background-color:#FFB2B2;
     visibility : hidden;
     font-weight:bold;
     font-size: 12px;
     box-shadow: 0 0 5px rgba(255, 0, 0, 1);


 }

.js file:

When you use submit then if perticular requirement not fill then it shows error!!

 $(document).ready(function()
      {
        $('#submit').click(function()
          {
            var uname = $('#name').val();
            if($('#name').val().match('[a-zA-Z]+\\.?')) {
              $("#nameerr").css("visibility", "hidden");

            }
            else {

              $("#nameerr").text("Name is InValid");
              $("#nameerr").css("visibility", "visible");
              return false;

            }

          }
        );    

        $('#submit').click(function()
          {
            var email = $('#email').val();
            if($('#email').val().match('[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}')) {
              $("#emailerr").css("visibility", "hidden");
            }
            else
            {
              $("#emailerr").text("Email Address is InValid.");
              $("#emailerr").css("visibility", "visible");

              return false;

            }

          }
        );



        $('#submit').click(function()
          {
            var email = $('#pass').val();
            if($('#pass').val().length<5) {
              $("#passerr").text("Minimum length should be 5");
              $("#passerr").css("visibility", "visible");
              return false;
            }
            else {
              $("#passerr").css("visibility", "hidden");

            }

          }
        );

     $('#submit').click(function(){

    var confirmpass = $('#confirmpassword').val();


    if($('#password').val() != $('#confirmpassword').val()) {
        $("#confirmpasserr").text("Password doesnt match");
      $("#confirmpasserr").css("visibility", "visible");
      return false;
    }
     else {
      $("#confirmpasserr").css("visibility", "hidden");

    }

});



        $('#email').on("blur", function()
          {

            if($('#err').val.match($msg)) {

              $("#err").text($msg);
              $("#err").css("visibility", "visible");

            }
            else {

              $("#err").css("visibility", "hidden");
            }

          }
        );
      }
    );
Robey answered 20/10, 2015 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.