【问题标题】:Ajax submit validations do nothing after success responseAjax 提交验证在成功响应后什么都不做
【发布时间】:2020-10-16 18:55:50
【问题描述】:

我想在提交按钮验证后提交表单。验证更正并完成后,错误和警告消失,但此脚本什么也不做。我点击了提交按钮,它只是没有响应,也没有将任何数据插入数据库。

顺便说一下,我在每个单独的 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

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();
    }
    
}
?>

【问题讨论】:

  • 您执行这么多 ajax 请求的任何具体原因 - 您是否知道可以在一个请求中发送所有这些数据。如果您需要帮助,请告诉我
  • 能否请您也发布您的 PHP 代码?谢谢
  • AJAX 代码可以优化,但本身并没有错。问题出在你的 registercontrol.php
  • @AlwaysHelping 我现在发布了。
  • @Martin 我不这么认为,但我现在发布了也许你可以检查一下。

标签: javascript php jquery ajax pdo


【解决方案1】:

要注意的一件快速的事情是您可以优化 AJAX 功能。绝对没有理由发出那么多 AJAX 请求。您可以在一个 AJAX 请求中发送所有数据并完成所有成功功能。

另外需要注意的是,如果 post 变量 submit 存在,您的 PHP 代码将执行数据库逻辑。现在你根本不通过你的 AJAX 函数来解析它。您没有使用带有提交的序列化方法,而是解析非常具体的数据,通过指定每个元素的值手动获取。

您可以做的是将submit 解析为另一个数据变量。考虑到这个想法,我冒昧地优化了您的 AJAX 代码。

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

现在您肯定会有一个提交POST 变量,该变量将输入您的if() 语句以进行数据库插入。

您可以做的另一件事是更具体地检查您是否应该输入允许插入数据库的语句。现在它只围绕POST 变量提交。没有其他逻辑。您可能需要重新考虑这一点。创建以FALSE 开头的变量,然后当您的验证检查一切正常时,将它们设置为true。围绕它构建您的数据库插入的 if() 语句,因为这比提交变量是否存在更相关。

另一件事是您使用md5() 散列函数作为您的密码。这是非常不安全的。参考this article

您也没有在告诉用户单击激活链接的行上正确连接 PHP 变量。你连接了你的 super globals 就好了,但不是 PHP 变量。

话虽如此,除了我指出的以外,没有什么本质上的错误。

这是您的 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();
    }
}
?>

我将委托$someVar-&gt;isValid() 指的是有效的东西,因为我对此没有其他见解。

如果您现在在数据库插入之外还有其他错误,则问题出在其他地方。要么你没有遵循你的表结构逻辑(错别字、无效数据格式等)

【讨论】:

  • 它正在工作,谢谢,我将进一步更改散列函数。还要感谢您的 Ajax 优化,但您的优化显示了每个 div 元素内的每个输入验证。我的意思是例如“请填写此字段”在#vusername 和其他人中重复了 4 次。
  • 现在应该修复了。
  • 您需要告诉错误消息它们应该具体去哪里。 response 等于 html 这意味着在 registercontrol.php 页面中找到的任何 html 都将是放入这些元素中。您需要围绕它构建一个逻辑,以便正确显示每个错误。
  • 看来我需要更多合乎逻辑的方法。我会试试的。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
相关资源
最近更新 更多