无法通过Ajax检查和验证数据库中已经存在的UserId(用户名)

时间:2018-08-06 11:07:57

标签: php jquery ajax

我不知道为什么我的代码无法正常工作。我想验证用户是否已经以register.php的注册形式存在错误,我所有的代码在user.php和process.php中都可以正常运行,但是当我尝试向现有的userid注册时,它不会重定向到register.php (用户名),什么也没有发生,当我尝试使用新的用户名(用户名)注册时,数据存储在数据库中,但没有重定向到index.php,这是什么问题,请帮帮我。我还在github中发布了我的代码,链接为:https://github.com/bloodseeker2018/inv_project 请帮助我我的代码有什么问题。我搜寻了我能做的一切。 我想做的是,如果有人尝试向新用户注册,它应该警告用户已经存在,并且如果有人尝试向新用户ID(用户名)注册,它将存储在数据库中并重定向到index.php 请帮助我..如果有人帮助我,我将非常感激。 register.php是:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes">
        <title> Inventory Management System </title>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="./css/style.css">
        <script type="text/javascript" src="./js/main.js"></script>
        <script type="text/javascript" src="./js/validation.js"></script>
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">    
    </head>
<body>
<?php //Navbar
include_once("./templates/header.php");
?>
<br/><br/>
<div class="container">
    <div class="card mx-auto shadow p-3 mb-5 bg-white rounded" style="width: 25rem;">
        <div class="card-header">Add Users</div>
            <div class="card-body">
                <form id="register_form" name="register_form"  method="post" action="register.php">
                    <div class="form-group mx-auto">                
                        <label for="fullname">Full Name*</label>&nbsp;&nbsp;<i class="fas fa-info-circle" ><span class="infotext">Your First Name and Last Name should be minimum of 3 character</span></i>
                        <div class="row">
                            <div class="col-md-6">                                      
                                <input type="text" class="form-control" name="firstname" id="firstname" placeholder="First Name" maxlength="20" data-validation="required" />
                                <span id="error_firstname" class="text-danger" style="font-size: 12px;"></span>                 
                            </div>                          
                            <div class="col-md-6">  
                                <input type="text" class="form-control" name="lastname" id="lastname" placeholder="Last Name" maxlength="20" data-validation="required"/>                           
                                <span id="error_lastname" class="text-danger" style="font-size: 12px;"></span>
                            </div>
                        </div>                          
                    </div>  
                    <div class="form-group mx-auto">
                        <label for="username">User Id*</label>
                        <input type="text" class="userid form-control" id="username" name="username" placeholder="This will be your login User Id" maxlength="50" autocomplete="off"/>                              
                        <span id="error_username" class="text-danger" style="font-size: 12px;"></span>                      
                    </div>
                    <div class="form-group mx-auto">
                        <label for="password1">Password*</label>
                        <input type="password" class="password1 form-control" id="password1" name="password1" placeholder="Password">   
                        <input type="checkbox" id="showHide"/>
                        <label for="showHide" id="showHideLabel"><font class="form-text text-muted" size="2">Show Password</font></label><br/>
                        <span id="error_password1" class="text-danger" style="font-size: 12px;"></span>                     
                    </div>
                    <div class="form-group">
                        <label for="Password2">Re-Enter Password*</label>
                        <input type="password" class="form-control" id="password2" name="password2" placeholder="Re-type your Password">
                        <span id="error_password2" class="text-danger" style="font-size: 12px;" ></span>                        
                    </div>
                    <div class="form-group">
                        <label for="usertype">User Type*</label>
                        <select name="usertype" class="form-control" id="usertype">
                            <option value="" selected="selected" hidden disabled="disabled">Select</option>                         
                            <option value="Administrator">Administrator</option>                                
                            <option value="Normal_User">Normal User</option>                            
                        </select>
                        <span id="error_usertype" class="text-danger" style="font-size: 12px;"></span>
                    </div>  
                    <div class="form-group">
                        <button type="submit" value="submit" id="submit" class="btn btn-primary"><i class="fa fa-plus">&nbsp;</i>Add</button>
                    </div>

        <!--            <button type="submit" value="submit" id="submit" class="btn btn-primary" style="background-color: #008000"><i class="fa fa-unlock">&nbsp;</i><span><a href="index.php" style="color: white; text-decoration: none; font-weight: 100; font-family: sans-serif;"> Login</span></button>  -->
                </form>
            </div>      
    <div class="card-footer text-muted">Please fill in all the compulsory(*) fields above
    </div>
    </div>
</div>
</body>
</html>

index.php是:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes">
        <title> Inventory Management System </title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="./css/style.css">
        <script type="text/javascript" src="./js/main.js"></script> 
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
    </head>
    <body>
        <?php //Navbar
        include_once("./templates/homeheader.php");
        ?>
    </br></br>
        <div class="container">
            <div class="card mx-auto shadow-lg p-3 mb-5 bg-white rounded " id="firstclass" style="width:20rem;">
                <br/>
                <img class="card-img-top mx-auto" style="width: 60%;" src="./images/adbl.png" id="LoginIcon">
                <div class="card-body">
                            <form>
                                <div class="form-group">
                                    <label for="username">User ID</label>
                                     <div class="input-container">
                                    <input type="text" class="username form-control" name="username" id="username"  placeholder="Input your Username">  
                                    </div>                          
                                    <small id="textHelp" class="form-text text-muted"> We'll never share your User Id with anyone else.</small>
                                </div>      
                                <div class="form-group">
                                    <label class="control-label" for="Password"> Password </label>
                                    <input type="password" name="Password" class="password form-control" placeholder="Password">                        
                                    <input type="checkbox" id="showHide"> 
                                    <label for="showHide" id="showHideLabel"><font class="form text text-muted"size="2" > Show Password </font></label>                                         
                                </div>                                  
                                    <button type="submit" class="btn btn-primary"><i class="fa fa-unlock">&nbsp;</i>Login</button>
                            </form>
                </div>             
                <div class="card-footer"><a href="http://localhost/inv_project/public_html/register.php#">Forgot Password ?</a></div>
            </div>          
        </div>
        </body>
</html> 

validation.js是:

$(document).ready(function(){
    var DOMAIN = "http://localhost/inv_project/public_html";
    $flag = 1;
    function validateFirstname(sFirstname) {
        var filter = /^[a-zA-Z]*$/;
        if (filter.test(sFirstname)) {
            return true;
        } else {
            return false;
        }
    }
    $("#firstname").focusout(function () {
        var sFirstname = $('#firstname').val();
        if ($.trim(sFirstname).length == 0) {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_firstname").text("Enter your First Name");
            e.preventDefault();
        } else if ($(this).val().length < 3 ) {
                 $(this).css("border-color", "#cd2d00");
                 $('#submit').attr('disabled', true);
                 $("#error_firstname").text("Too short First Name");
        } else if (validateFirstname(sFirstname)) {
            $(this).css("border-color", "#2eb82e");
            $('#submit').attr('disabled', false);
            $("#error_firstname").text("");;
        } else {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_firstname").text("Invalid First Name");
            e.preventDefault();
        }
    });
    function validateLastname(sLastname) {
        var filter1 = /^[a-zA-Z]*$/;
        if (filter1.test(sLastname)) {
            return true;
        } else {
            return false;
        }
    }
    $("#lastname").focusout(function () {
        var sLastname = $('#lastname').val();
        if ($.trim(sLastname).length == 0) {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_lastname").text("Enter your Last Name");
            e.preventDefault();
        } else if ($(this).val().length < 3 ) {
                 $(this).css("border-color", "#cd2d00");
                 $('#submit').attr('disabled', true);
                 $("#error_lastname").text("Too short Last Name");
        } else if (validateLastname(sLastname)) {
            $(this).css("border-color", "#2eb82e");
            $('#submit').attr('disabled', false);
            $("#error_lastname").text("");;
        } else {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_lastname").text("Invalid Last Name");
            e.preventDefault();
        }
    });
    function validateUsername(sUsername) {
        var filter2 = /^(?=.*[a-z])[a-z0-9]+(([\.-]?)[a-z0-9]+)*(([\._]?)[a-z0-9]+)*(([\_-]?)[a-z0-9]+)*$/;
        if (filter2.test(sUsername)) {
            return true;
        } else {
            return false;
        }
    }
    $("#username").focusout(function () {
        var sUsername = $('#username').val();
        if ($.trim(sUsername).length == 0) {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_username").text("Enter your User Id");
            e.preventDefault();
        } else if ($(this).val().length < 7 ) {
                 $(this).css("border-color", "#cd2d00");
                 $('#submit').attr('disabled', true);
                 $("#error_username").text("Too short User Id");
        } else if (validateUsername(sUsername)) {
            $(this).css("border-color", "#2eb82e");
            $('#submit').attr('disabled', false);
            $("#error_username").text("");;
        } else {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_username").text("Invalid User Id");
            e.preventDefault();
        }
    });
    function validateUsertype(){
        if (document.register_form.usertype.value == ""){
            return false;
        } else {
            return true;
        }
    }
    $("#usertype").focusout(function () {
        if (!validateUsertype()){
                $(this).css("border-color", "#cd2d00");
                $('#submit').attr('disabled', true);
                $("#error_usertype").text("Select a User Type");
            } else {
                $(this).css("border-color", "#2eb82e");
                $('#submit').attr('disabled', false);
                $("#error_usertype").text("");
        }
    });
    function validatePassword(sPassword) {
        var filter3 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/;
        if (filter3.test(sPassword)) {
            return true;
        } else {
            return false;
        }
    }
    $("#password1").focusout(function () {
        var sPassword = $('#password1').val();
        if ($.trim(sPassword).length == 0) {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_password1").text("Enter a Password");
            e.preventDefault();
        } else if ($(this).val().length < 9 ) {
                 $(this).css("border-color", "#cd2d00");
                 $('#submit').attr('disabled', true);
                 $("#error_password1").text("Too short Password");
        } else if (validatePassword(sPassword)) {
            $(this).css("border-color", "#2eb82e");
            $('#submit').attr('disabled', false);
            $("#error_password1").text("");;
        } else {
            $(this).css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_password1").text("Invalid Password");
            e.preventDefault();
        }
    });
    $("#password2").focusout(function () {
        var sPassword = $('#password1').val();
        if (validatePassword(sPassword)){
            if ($("#password2").val() !== $("#password1").val()) {
                $("#password2").css("border-color", "#cd2d00");
                $('#submit').attr('disabled', true);
                $("#error_password2").text("Passwords Do not match");
            } else if (($("#password2").val() == $("#password1").val()) && $("#password1").val() !== '') {
                $(this).css("border-color", "#2eb82e");
                $('#submit').attr('disabled', false);
                $("#error_password2").text("");
            }
        } else if (!validatePassword(sPassword)){
                $("#password2").css("border-color", "");
                $('#submit').attr('disabled', true);
                $("#error_password2").text("");
                $("#password2").val('');       
        }
    });

    $("#submit").click(function () {
        if ($("#firstname").val() == '') {
            $("#firstname").css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true); 
            $("#error_firstname").text("Enter your First Name"); 
        }
        if ($("#lastname").val() == '') {
            $("#lastname").css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_lastname").text("Enter your Last Name");
        }
        if ($("#username").val() == '') {
            $("#username").css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_username").text("Enter your User Id");
        }
        if ($("#password1").val() == '') {
            $("#password1").css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_password1").text("Enter a Password");
        }
        if (!validateUsertype()){
                $("#usertype").css("border-color", "#cd2d00");
                $('#submit').attr('disabled', true);
                $("#error_usertype").text("Select a User Type");
        }
        if ($("#password2").val() == '' && $("#password1").val() !== '') {
            $("#password2").css("border-color", "#cd2d00");
            $('#submit').attr('disabled', true);
            $("#error_password2").text("Confirm your Password");
        } else if (validatePassword($("#password1").val())){
              if (!($('#submit').is('disabled', true))){ 
                if (($("#password2").val() == $("#password1").val()) && $("#password1").val() !== '') {
                    $.ajax({
                        url : DOMAIN+"/includes/process.php",
                        method : "POST",
                        data : $("#register_form").serialize(),
                        success : function(data){
                            if (data == "USER_ALREADY_EXISTS"){
                                alert("User Id is already used");
                            } else if (data == "SOME_ERROR"){
                                alert("Something is Wrong");
                            }else {
                                window.location.href = encodeURI(DOMAIN+"/index.php?msg=You are registered Now you can login");
                            }
                        }

                    })                
                } 
            }
        }
    })   
});

main.js是:

$(document).ready(function(){
    $("#showHide").click(function(){
        if ($(".password1").attr("type")=="password"){
            $(".password1").attr("type","text");
        } else {
            $(".password1").attr("type","password");
        }                           
    });
    $("#showHide").click(function(){
        if ($(".password").attr("type")=="password"){
            $(".password").attr("type","text")
        } else {
            $(".password").attr("type","password")
        }                           
    });

    $(".dropdown").hover(            
        function() {
                $('.dropdown-menu', this).stop( true, true ).fadeIn("slow");
                $(this).toggleClass('open');
                $('b', this).toggleClass("caret caret-up");                
        },
        function() {
                $('.dropdown-menu', this).stop( true, true ).fadeOut("fast");
                $(this).toggleClass('open');
                $('b', this).toggleClass("caret caret-up");                
        });
});

process.php是:

<?php
include_once("../database/constants.php");
include_once("user.php");
if (isset($_POST["username"])) {
    $user = new User();
    $result = $user->createUserAccount($_POST["username"],$_POST["firstname"],$_POST["lastname"],$_POST["password1"],$_POST["usertype"]);
    echo $result;
}
?>

user.php是:

<?php
class User
{
    private $con;
    function __construct()
    {   
        include_once("../database/db.php");
        $db = new Database();
        $this->con = $db->connect();    
    }
    private function usernameExists($username){
        $pre_stmt = $this->con->prepare("SELECT `id` FROM `user` where `username` = ?");
        $pre_stmt->bind_param("s",$username);
        $pre_stmt->execute() or die($this->con->error);
        $result = $pre_stmt->get_result();      
        if ($result->num_rows > 0){
            return 1;       
        }else {
            return 0;
        }
    }
    public function createUserAccount($username,$firstname,$lastname,$password1,$usertype){
        if($this->usernameExists($username)){
            return "USER_ALREADY_EXISTS";
        }else{
            $pass_hash = password_hash($password1,PASSWORD_BCRYPT,["cost"=>8]);
            $date = date("Y-m-d");
            $remarks ="";
            $pre_stmt = $this->con->prepare("INSERT INTO `user`(`username`,`firstname`, `lastname`, `password`, `usertype`, `register_date`, `last_login`, `remarks`) VALUES (?,?,?,?,?,?,?,?)");
            $pre_stmt->bind_param("ssssssss",$username,$firstname,$lastname,$pass_hash,$usertype,$date,$date,$remarks);
            $result = $pre_stmt->execute() or die($this->con->error);
            if ($result){
                return $this->con->insert_id;
            }else{
                return "SOME_ERROR";
            }
        }       
    }
    public function userLogin($username,$password1){
        $pre_stmt = $this->con->prepare("SELECT id,username,firstname,lastname,password,usertype,last_login FROM user WHERE username = ?");
        $pre_stmt->bind_param("s",$username);
        $pre_stmt->execute() or die($this->con->error);
        $result = $pre_stmt->get_result();
        if($result->num_rows < 1){
            return "NOT_REGISTERED";
        }else{
            $row = $result->fetch_assoc();
            if (password_verify($password1,$row["password"])){
                $_SESSION["userid"] = $row["id"];
                $_SESSION["firstname"] = $row["firstname"];
                $_SESSION["lastname"] = $row["lastname"];
                $_SESSION["usertype"] = $row["usertype"];
                $_SESSION["last_login"] = $row["last_login"];
                $last_login = date("Y-m-d h:m:s");
                $pre_stmt = $this->con->prepare("UPDATE user  SET last_login = ? WHERE username = ?");
                $pre_stmt->bind_param("ss",$last_login,$username);
                $result = $pre_stmt->execute() or die($this->con->error);
                if ($result){
                    return 1;
                }else{
                    return 0;
                }
            }else{
                return "PASSWORD_NOT_MATCHED";
            }
        }
    }
}
?>

constants.php是:

<?php

session_start();
define("HOST","localhost");
define("USER","root");
define("PASS","");
define("DB","project_inv");
define("DOMAIN","http://localhost/inv_project/public_html");


?>

db.php是:

<?php


class Database
{
    private $con;

    public function connect(){
        include_once("constants.php");
        $this->con = new Mysqli(HOST,USER,PASS,DB);
        if ($this->con) {           
            return $this->con;
        }       
        return "DATABASE_CONNECTION_FAIL";      
    }

}
?>

0 个答案:

没有答案