简体   繁体   English

Ajax 提交验证成功响应后什么也不做

[英]Ajax submit validations do nothing after success response

I want to submit form after validations of submit button.我想在验证提交按钮后提交表单。 After validations corrected and completed error and warnings disappear but this script do nothing.验证更正并完成后,错误和警告消失,但此脚本什么也不做。 I clicked submit button its just not responding and not inserting any data into database.我单击了提交按钮,它只是没有响应并且没有将任何数据插入数据库。

By the way I showed every inputs validations in each induvidual div elements so I don't want to break this style too.顺便说一句,我在每个单独的 div 元素中显示了每个输入验证,所以我也不想打破这种风格。

<script type="text/javascript">
    $(document).ready(function(){       
        $('#submit').click(function(event){
            event.preventDefault();         
            var fullname = $("#fullname").val();
            var username = $("#username").val();
            var email = $("#email").val();
            var password = $("#password").val();            
            $.ajax({
                url: 'registercontrol.php',
                method: 'POST',
                data: {fullname:fullname},
                success:function(response){                 
                    $("#vfullname").html(response);                 
                }
            });
            $.ajax({
                url: 'registercontrol.php',
                method: 'POST',
                data: {username:username},
                success:function(response){                 
                    $("#vusername").html(response);                 
                }
            });
            $.ajax({
                url: 'registercontrol.php',
                method: 'POST',
                data: {email:email},
                success:function(response){                 
                    $("#vemail").html(response);                    
                }
            });
            $.ajax({
                url: 'registercontrol.php',
                method: 'POST',
                data: {password:password},
                success:function(response){                 
                    $("#vpassword").html(response);                 
                }
            });                     
        });
    });
</script>

registercontrol.php寄存器控制.php

<?php

require('../includes/config.php');

if(isset($_POST['fullname'])){
    //fullname validation
    $fullname = $_POST['fullname'];

    if (empty($_POST['fullname'])) {
        $warningfn = "Please fill this field";
        echo '<style type="text/css"> #fullname {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningfn.'</p>';
    }
    elseif (! $user->isValidFullname($fullname)){
        $infofn = 'Your name must be alphabetical characters';
        echo '<style type="text/css"> #fullname {border-color: #36b9cc !important;} </style>';
        echo '<p class="p-3 text-info">'.$infofn.'</p>';
    }   
    else {
        echo '<style type="text/css"> #fullname {border-color: #1cc88a !important;} </style>';
    }   
}

if(isset($_POST['username'])){
    //username validation
    $username = $_POST['username'];
    
    if (empty($_POST['username'])) {
        $warningun = "Please fill this field";
        echo '<style type="text/css"> #username {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningun.'</p>';
    }
    elseif (! $user->isValidUsername($username)){
        $infoun = 'Your username must be at least 3 alphanumeric characters';
        echo '<style type="text/css"> #username {border-color: #36b9cc !important;} </style>';
        echo '<p class="p-3 text-info">'.$infoun.'</p>';
    }
    elseif (! $user->isUsernameAlreadyinUse($username)){
        $errorun = 'This username already in use';
        echo '<style type="text/css"> #username {border-color: #e74a3b !important;} </style>';
        echo '<p class="p-3 text-danger">'.$errorun.'</p>';
    }
    else {
        echo '<style type="text/css"> #username {border-color: #1cc88a !important;} </style>';
    }   
}

if(isset($_POST['email'])){
    //email validation
    $email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
    
    if (empty($_POST['email'])) {
        $warningm = "Please fill this field";
        echo '<style type="text/css"> #email {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningm.'</p>';
    }
    elseif (! $user->isValidEmail($email)){
        $warningm = 'Please enter a valid email address';
        echo '<style type="text/css"> #email {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningm.'</p>';
    }
    elseif (! $user->isEmailAlreadyinUse($email)){
        $errorm = 'This email already in use';
        echo '<style type="text/css"> #email {border-color: #e74a3b !important;} </style>';
        echo '<p class="p-3 text-danger">'.$errorm.'</p>';
    }
    else {
        echo '<style type="text/css"> #email {border-color: #1cc88a !important;} </style>';
    }
}

if(isset($_POST['password'])){

    $password= $_POST['password'];

    if (empty($_POST['password'])) {
        $warningpw = "Please fill this field";
        echo '<style type="text/css"> #password {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningpw.'</p>';
    }
    elseif (! $user->isValidPassword($password)){
        $warningpw = 'Your password must be at least 6 characters long';
        echo '<style type="text/css"> #password {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningpw.'</p>';      
    }
    else {
        echo '<style type="text/css"> #password {border-color: #1cc88a !important;} </style>';
    }   
}

if (isset($_POST['gender'])) {
    $gender = $_POST['gender'];
    if (!in_array($gender, ['Male','Female','Other'])) {
        $gender = 'Other';
    }
} else {
    $gender = 'Other';
}

//if form has been submitted process it
if(isset($_POST['submit'])){    

    //hash the password
    $hashedpassword = password_hash($_POST['password'], PASSWORD_BCRYPT);

    //create the activasion code
    $activasion = md5(uniqid(rand(),true));

    try {

        //insert into database with a prepared statement
        $stmt = $db->prepare('INSERT INTO members (fullname,username,password,email,gender,active) VALUES (:fullname, :username, :password, :email, :gender, :active)');
        $stmt->execute(array(
            ':fullname' => $fullname,
            ':username' => $username,
            ':password' => $hashedpassword,
            ':email' => $email,
            ':gender' => $gender,
            ':active' => $activasion
        ));
        $id = $db->lastInsertId('memberID');

        //send email
        $to = $_POST['email'];
        $subject = "Confirm Your Account";
        $body = "<p>Thank you for registering on the demo site.</p>
        <p>Hello ".$fullname.", please click this link to activate your account: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>";

        $mail = new Mail();
        $mail->setFrom(SITEEMAIL);
        $mail->addAddress($to);
        $mail->subject($subject);
        $mail->body($body);
        $mail->send();

        //redirect to index page
        header('Location: register.php?action=joined');
        exit;

    //else catch the exception and show the error.
    } catch(PDOException $e) {
        $error[] = $e->getMessage();
    }
    
}
?>

One quick thing to notice is that you can optimize your AJAX function.一件需要注意的快速事情是,您可以优化 AJAX function。 There is absolutely no reason to make that many AJAX requests.绝对没有理由提出那么多 AJAX 请求。 You can send all of your data and do all of your success functionality in one AJAX request.您可以在一个 AJAX 请求中发送所有数据并执行所有成功功能。

Another thing to notice is that your PHP code performs the database logic if the post variable submit exists.另一件需要注意的是,如果 post 变量submit存在,您的 PHP 代码将执行数据库逻辑。 Right now you do not parse that through your AJAX function at all.现在你根本不通过你的 AJAX function 来解析它。 You are not using a serialize method with a submit, but you're parsing very specific data, fetched manually by specifying each elements value.您没有使用带有提交的序列化方法,但您正在解析非常具体的数据,通过指定每个元素值手动获取。

What you could do, is parse submit as another data variable.您可以做的是submit解析为另一个数据变量。 I took the liberty to optimize your AJAX code with that idea in mind.考虑到这个想法,我冒昧地优化了您的 AJAX 代码。

jQuery AJAX Example: jQuery AJAX 示例:

$(document).ready(function() {       
    $('#submit').click(function(event) {
        event.preventDefault();
        var fullname = $("#fullname").val();
        var username = $("#username").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var submit = "1";
        
        $.ajax({
            url: 'registercontrol.php',
            method: 'POST',
            data: {
                fullname : fullname,
                username : username,
                email : email,
                password : password,
                submit : submit
            },
            success:function(response){                 
                $("#vfullname").html(response);
                $("#vusername").html(response);
                $("#vemail").html(response);
                $("#vpassword").html(response);  
            }
        });                     
    });
});

Now you will for sure have a submit POST variable that will enter your if() statement for the database inserts.现在您肯定会有一个提交POST变量,该变量将输入您的if()语句以进行数据库插入。

Another thing you could do is have more concrete checks on whether you should enter the statement that allows for database insertion or not.您可以做的另一件事是更具体地检查您是否应该输入允许插入数据库的语句。 Right now it only revolves around the POST variable submit.现在它只围绕POST变量提交。 No other logic.没有其他逻辑。 You might want to reconsider that.您可能需要重新考虑这一点。 Make variables that start out as FALSE then when everything is okay with your validation checks, set them to true.使变量开始为FALSE ,然后当您的验证检查一切正常时,将它们设置为 true。 Construct your database insertion´s if() statement around that instead, as that is way more relevant than whether a submit variable exists or not.围绕它构建你的数据库插入的if()语句,因为这比提交变量是否存在更相关。

Another thing is that you're using an md5() hashing function for your password.另一件事是您使用md5()散列 function 作为您的密码。 This is highly insecure.这是非常不安全的。 Refer to this article .参考这篇文章

You were also not concatenating the PHP variables properly on the line where you're telling the user to click the activation link.您也没有在告诉用户单击激活链接的行上正确连接 PHP 变量。 You concatenated your super globals just fine, but not the PHP variables.你连接你的super globals就好了,但不是 PHP 变量。

With that said, there's nothing inherently wrong, other than what I pointed out.话虽如此,除了我指出的之外,没有什么本质上的错误。

Here is your PHP code:这是您的 PHP 代码:

<?php
if( isset( $_POST['fullname'] ) ) {
    //fullname validation
    $fullname = $_POST['fullname'];

    if( empty( $_POST['fullname'] ) ) {
        $warningfn = "Please fill this field";
        echo '<style type="text/css"> #fullname {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningfn.'</p>';
    } else if( !$user->isValidFullname($fullname) ) {
        $infofn = 'Your name must be alphabetical characters';
        echo '<style type="text/css"> #fullname {border-color: #36b9cc !important;} </style>';
        echo '<p class="p-3 text-info">'.$infofn.'</p>';
    } else {
        echo '<style type="text/css"> #fullname {border-color: #1cc88a !important;} </style>';
    }   
}

if( isset( $_POST['username'] ) ) {
    //username validation
    $username = $_POST['username'];
    
    if( empty( $_POST['username'] ) ) {
        $warningun = "Please fill this field";
        echo '<style type="text/css"> #username {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningun.'</p>';
    } else if( !$user->isValidUsername($username) ) {
        $infoun = 'Your username must be at least 3 alphanumeric characters';
        echo '<style type="text/css"> #username {border-color: #36b9cc !important;} </style>';
        echo '<p class="p-3 text-info">'.$infoun.'</p>';
    } else if ( !$user->isUsernameAlreadyinUse($username) ) {
        $errorun = 'This username already in use';
        echo '<style type="text/css"> #username {border-color: #e74a3b !important;} </style>';
        echo '<p class="p-3 text-danger">'.$errorun.'</p>';
    } else {
        echo '<style type="text/css"> #username {border-color: #1cc88a !important;} </style>';
    }   
}

if( isset( $_POST['email'] ) ) {
    //email validation
    $email = htmlspecialchars_decode( $_POST['email'], ENT_QUOTES );
    
    if( empty( $_POST['email'] ) ) {
        $warningm = "Please fill this field";
        echo '<style type="text/css"> #email {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningm.'</p>';
    } else if( !$user->isValidEmail($email) ) {
        $warningm = 'Please enter a valid email address';
        echo '<style type="text/css"> #email {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningm.'</p>';
    } else if( !$user->isEmailAlreadyinUse($email) ) {
        $errorm = 'This email already in use';
        echo '<style type="text/css"> #email {border-color: #e74a3b !important;} </style>';
        echo '<p class="p-3 text-danger">'.$errorm.'</p>';
    } else {
        echo '<style type="text/css"> #email {border-color: #1cc88a !important;} </style>';
    }
}

if( isset( $_POST['password'] ) ) {
    $password= $_POST['password'];

    if( empty( $_POST['password'] ) ) {
        $warningpw = "Please fill this field";
        echo '<style type="text/css"> #password {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningpw.'</p>';
    } else if ( !$user->isValidPassword($password) ) {
        $warningpw = 'Your password must be at least 6 characters long';
        echo '<style type="text/css"> #password {border-color: #f6c23e !important;} </style>';
        echo '<p class="p-3 text-warning">'.$warningpw.'</p>';      
    } else {
        echo '<style type="text/css"> #password {border-color: #1cc88a !important;} </style>';
    }   
}

if( isset( $_POST['gender'] ) ) {
    $gender = $_POST['gender'];
    if( !in_array($gender, ['Male','Female','Other']) ) {
        $gender = 'Other';
    }
} else {
    $gender = 'Other';
}

if( isset( $_POST['submit'] ) ) {
    //hash the password
    $hashedpassword = password_hash( $password, PASSWORD_BCRYPT );

    //create the activasion code
    // this is highly insecure, see: https://www.php.net/manual/en/function.md5.php
    $activasion = md5( uniqid( rand(),true ) );

    try {
        //insert into database with a prepared statement
        $stmt = $db->prepare('INSERT INTO members (fullname,username,password,email,gender,active) VALUES (:fullname, :username, :password, :email, :gender, :active)');
        $stmt->execute(array(
            ':fullname' => $fullname,
            ':username' => $username,
            ':password' => $hashedpassword,
            ':email' => $email,
            ':gender' => $gender,
            ':active' => $activasion
        ));
        $id = $db->lastInsertId('memberID');

        //send email
        $to = $_POST['email'];
        $subject = "Confirm Your Account";
        $body = "<p>Thank you for registering on the demo site.</p>
                 <p>Hello ".$fullname.", please click this link to activate your account: <a href='".DIR."activate.php?x=".$id."&y=".$activasion."'>".DIR."activate.php?x=".$id."&y=".$activasion."</a></p>";

        $mail = new Mail();
        $mail->setFrom(SITEEMAIL);
        $mail->addAddress($to);
        $mail->subject($subject);
        $mail->body($body);
        $mail->send();

        //redirect to index page
        header('Location: register.php?action=joined');
        exit;

      //else catch the exception and show the error.
    } catch(PDOException $e) {
        $error[] = $e->getMessage();
    }
}
?>

I will entrust that $someVar->isValid() refers to something that works as I have no other insight on that.我将委托$someVar->isValid()指的是有效的东西,因为我对此没有其他见解。

If you're having further errors outside of the database insertion now, the problem lies elsewhere.如果您现在在数据库插入之外还有其他错误,则问题出在其他地方。 Either you're not following your table structure logic (typos, invalid data formats etc.)要么你没有遵循你的表结构逻辑(错别字、无效的数据格式等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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