在以HTML格式输入用户名时验证用户名

时间:2018-03-20 02:09:15

标签: php jquery html5

我有一个数据库(通过UwAmp),其上有一个存储用户详细信息的表,我想在用户输入时验证用户名表单,以检查他们的用户名是否已被占用。我尝试过几件事情,并且我已经被推荐使用ajax,但我似乎无法让它工作。

HTML和php

 require_once 'config.php';//Connect to the database

// 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 a username.";
    } else{
        // Prepare a select statement
        $sql = "SELECT id FROM userdetails WHERE username = ?";

        if($stmt = mysqli_prepare($link, $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_err = "Username is already taken.";
                } else{
                    $username = trim($_POST["username"]);
                }
            } 

        }

        // Close statement
          mysqli_stmt_close($stmt);

    }



    // Validate password
    if(empty(trim($_POST['password']))){
        $password_err = "Please enter a password.";     
    } elseif(strlen(trim($_POST['password'])) < 4){
        $password_err = "Password must have at least 4 characters.";
    } else{
        $password = trim($_POST['password']);
    }

    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $confirm_password_err = 'Please confirm password.';     
    } else{
        $confirm_password = trim($_POST['confirm_password']);
        if($password != $confirm_password){
            $confirm_password_err = 'Password did not match.';
        }
    }

    // Check for errors before submitting into database
    //Saves on complicaitons
    if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){

        // Prepare an insert statement
        $sql = "INSERT INTO userdetails (username, password) VALUES (?, ?)";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);

            // Set parameters
            $param_username = $username;
            $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Redirect to login2 page if successful
                header("location: login2.php");
            } 
        }

        // Close statement
        mysqli_stmt_close($stmt);

    }

    // Close connection
    mysqli_close($link);
}
?>

HTML文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Register</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/script.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>





    <div class="parent">


      <!--Form login, using bootstrap and own css styling-->
      <div class="form_login">


               <h2 class="title">Sign Up</h2>


<form name ="credentials" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" onsubmit="return validateForm()" onKeyPress="return checkSubmit(event)">
            <div class="formGroups">

                <input type="text" id="username" name="username"class="form-control"  placeholder="Username">
                <span id="username">Waiting for user input...</span>
                <span id="errmsg"><?php echo $username_err; ?></span>
            </div>    
            <div class="formGroups">

                <input type="password" id="password" name="password" class="form-control" placeholder="Password">
                <span id="errmsgpass"><?php echo $password_err; ?></span>
            </div>
            <div class="formGroups">

                <input type="password" id="confirm" name="confirm_password" class="form-control" placeholder="Confirm Password">
                <span id="errmsgpassc"><?php echo $confirm_password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Submit">
                <input type="reset" class="btn btn-default" value="Reset">
            </div>
            <p>Already have an account? <a href="login2.php">Login here</a>.</p>
        </form>


          </div>




      </div>


  </body>
</html>

脚本。

jQuery(function($) {

    // When the user types something in the input
    $('#username').on('keyup', function(e) {

        // set the variables
        var $input = $(this)
        ,   value  = $input.val()
        ,   data   = {
                username: value   
        };

        // perform an ajax call
        $.ajax({
            url: 'validator.php', // this is the target
            method: 'get', // method
            data: data, // pass the input value to server
            success: function(r) { // if the http response code is 200
                $('#username').css('color', 'green').html(r);
                $('button').removeAttr('disabled');
            },
            error: function(r) { // if the http response code is other than 200
                $('#username').css('color', 'red').html(r);
                $('button').attr('disabled', 'disabled');
            }

        });
    });

});

Validator.php

<?php
if(isset($_GET['username'])) {
    $email = $_GET['username'];

    if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(200);
        echo 'The email '.$username.' is valid';
    } else {
        http_response_code(412);
        echo 'The email '.$username.' is not valid';
    }
}

有人会就如何解决此问题提出任何建议吗?

0 个答案:

没有答案