简体   繁体   中英

How can I submit a html form for server-side validation after successful client-side validation with jQuery?

I am currently working on a web application project. I have completed the design of the registration page. I have used jQuery for input validation, and so far everything is working as expected. However, when I click on the Register (submit) button, the form does not submit. I am using php, MySQL, JavaScript, CSS, and Bootstrap for the task. Below is my code in register.php file:

**<?php
// Include config file
require_once "./config/connection.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Validate username
    if(empty(trim($_POST["username"])))
    {
        $username_err = "Please enter your email";
    }
    else
    {
        // Prepare a select statement
        $sql = "SELECT email FROM users WHERE username = ?";
        if($stmt = mysqli_prepare($con, $sql))
        {
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            // Set parameters
            $param_username = trim($_POST["username"]);
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt))
            {
                /* store result */
                mysqli_stmt_store_result($stmt);
                if(mysqli_stmt_num_rows($stmt) == 1)
                {
                    $username = trim($_POST["username"]);
                }
                else
                {
                    $username_err = "The email provided does not belong to your organization";
                }
            }
            else
            {
                echo "Oops! Something went wrong. Please try again later.";
            }
            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    // Close connection
    mysqli_close($con);
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <title>DEMO TELEPHONE DIRECTORY</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./bootsstrap/bootstrap-3.3.5-dist/css/bootstrap.min.css">
    <!-- <script src="/"jquery-ui-1.11.4/jquery-ui.min.js"  ></script> -->
    <link rel="stylesheet" href="./css/index.css" type="text/css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="./bootsstrap/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
    <script src="./js/register.js" type="text/javascript"></script>
  </head>
  <body>
    <div class="container-fluid">
      <div id="loginpanel">
        <form name="loginform" id="registrationform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
          <h1>Register</h1>
          <div class="form-group">
              <label for="usernameregistration">Email</label>
              <input class="form-control" id="usernameregistration" type="text" placeholder="Email" name="username" required autofocus/>
              <p id="usernameerror" class="alert-error  <?php echo (empty($username_err)) ? 'hideerror' : '';?>" role="alert"><?php echo $username_err; ?></p>
          </div>
          <div class="form-group">
              <label for="passwordregistration">Password</label>
              <input class="form-control" id="passwordregistration" type="password" placeholder="Password" name="password" required/>
              <p id="registrationpassworderror" class="alert-error hideerror" role="alert" ></p>
          </div>
          <div class="form-group">
            <div class="form-group">
                <label for="confirmpasswordregistration">Confirm Password</label>
                <input class="form-control" id="confirmpasswordregistration" type="password" placeholder="Confirm Password" name="confirmpassword" required/>
                <p id="confirmregistrationpassworderror" class="alert-error hideerror" role="alert"></p>
            </div>
            <div class="form-group">
              <button class="btn btn-primary btn-md btn-block" name="btnregister" id="btnregister" type="submit">Register</button>
          </div>
          <div class="form-group">
              <span>Already registered? </span><span><a href="./">Click here to login</a></span>
          </div>
        </form>
      </div>
    </div>
    <div class="clearfix"></div>
  </body>
</html>**

Below is my JavaScript code in register.js file:

**$(document).ready(function(){
  // Validate Username
  $('#usernameerror').html('').addClass('hideerror');
  let usernameerror = true;
  $('#usernameregistration').keyup(function () {
      validateUsername();
  });
  function validateUsername() {
    let username = $('#usernameregistration').val();
    if (username.length == '') {
        $('#usernameerror').html('Please enter your email').removeClass('hideerror');
        usernameerror = false;
        return false;
    }
    else {
        $('#usernameerror').html('').addClass('hideerror');
    }
  }
  // Validate Email
  $('#usernameerror').html('').addClass('hideerror');
  let emailerror = true;
  $('#usernameregistration').keyup(function () {
      validateEmail();
  });
  function validateEmail() {
    let email = $('#usernameregistration').val();
    if (email.length != '')
    {
      if (isEmail(email))
      {
        $('#usernameerror').html('').addClass('hideerror');
      }
      else
      {
        $('#usernameerror').html('The email is invalid').removeClass('hideerror');
        emailerror = false;
        return false;
      }
    }
  }
  function isEmail(email) {
    let regexEmail = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
    return regexEmail.test(email);
  }
  // Validate Password
  $('#registrationpassworderror').html('').addClass('hideerror');
  let passworderror = true;
  $('#passwordregistration').keyup(function () {
      validatePassword();
  });
  function validatePassword() {
    let password = $('#passwordregistration').val();
    if (password.length == '') {
        $('#registrationpassworderror').html('Please enter your password').removeClass('hideerror');
        passworderror = false;
        return false;
    }
    else if (password.length < 6) {
        $('#registrationpassworderror').html('Password length should be at least 6 characters').removeClass('hideerror');
        passworderror = false;
        return false;
    }
    else {
        $('#registrationpassworderror').html('').addClass('hideerror');
    }
  }
  // Validate Confirm Password
  $('#confirmregistrationpassworderror').html('').addClass('hideerror');
  let confirmpassworderror = true;
  $('#confirmpasswordregistration').keyup(function () {
      validateConfirmPassword();
  });
  function validateConfirmPassword() {
    let password = $('#passwordregistration').val();
    let confirmpassword = $('#confirmpasswordregistration').val();
    if (confirmpassword.length == '') {
        $('#confirmregistrationpassworderror').html('Please confirm your password').removeClass('hideerror');
        confirmpassworderror = false;
        return false;
    }
    else if (confirmpassword != password) {
        $('#confirmregistrationpassworderror').html('Password and Confirm Password do not match').removeClass('hideerror');
        confirmpassworderror = false;
        return false;
    }
    else {
        $('#confirmregistrationpassworderror').html('').addClass('hideerror');
    }
  }
  // Submit button
  $('#btnregister').click(function () {
      validateUsername();
      validatePassword();
      validateConfirmPassword();
      validateEmail();
      if ((usernameerror == true) &&
          (passworderror == true) &&
          (confirmpassworderror == true) &&
          (emailerror == true)) {
          return true;
      } else {
          return false;
      }
  });
});**

Finally, below is my css code in index.css file:

**#loginpanel
{
    margin:0 auto;
    width: 300px;
    position: relative;
    top:150px;
    background-color: beige;
    padding:20px;
    border-radius: 0px;
}
#errormsg
{
    clear:both;
    position: relative;
    top:250px;
}
.hideerror
{
   display: none;
}
.alert-error
{
  color: red;
  margin-bottom: -15px;
}**

I am suspecting the my jQuery code to be the culprit but can't seem to figure out how to allow submit after successful input validation. Kindly help.

That's a lot of jquery code going on. I would advise to start with the basics, how do we prevent a form from submitting when user clicks the button:

<form onsubmit="validate(event)">
    <input name="var1" value="xxx">
    <button>Submit</button>
</form>

<script>
    function validate(event) {
        var formIsValid = true;
        
        if (formIsValid) {
            // let the browser submit the form.
        } else {
            // prevent the form submitting.
            event.preventDefault();
        }
    }
</script>

Whenever a submit button is clicked / the user attempts to submit the form we can listen to the 'submit' event.

If we call preventDefault on the submit event we can stop the user from submitting an invalid form.

In your example you could change the $('#btnregister').click function to $('form').submit(function(event) { event.preventDefault(); })

Try to send form use jQuery method submit if validation is ok

if ((usernameerror == true) &&
      (passworderror == true) &&
      (confirmpassworderror == true) &&
      (emailerror == true)) {
         $('#registrationform').submit();
  } else {
      return false;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM