在不重新加载页面PHP Ajax的情况下发送数据

时间:2016-05-23 09:12:33

标签: php jquery ajax form-submit

我正在尝试创建一个登录页面,其中,每次登录的尝试都会立即在页面上完成;而不是刷新页面。谷歌如何登录页面以及Facebook如何在不刷新的情况下提交消息的方式。

我已经用PHP编写了页面的后端功能,现在我想给它更多的东西,让它外观和功能异常。

这是我正在使用的当前Ajax脚本,它不希望以我希望的方式工作(我尝试了多个具有相同结果的其他脚本):

<script>
    $(function () {
        $('#_js_pdTr1').on('submit', function (e) {

            e.preventDefault();

            $.ajax({
                type: 'post',
                url: 'login_push.php',
                data: $('#_js_pdTr1').serialize(),
            });
        });
    });
</script>

这是页面的表单:

<form id="_js_pdTr1" action="" method="post">
    <h3>LOGIN</h3>
    <div class="err-disp-out">
        <?php
            if(!empty($errors)){
                echo output_errors($errors);
            }
        ?>
    </div>
    <input type="text" name="username" placeholder="Username"><br><br>
    <input type="password" name="password" placeholder="Password"><br><br>
    <input id="remember" type="checkbox" name="remember_me"><label for="remember">Remember Me</label><br><br>
    <button id="_js_pdTr2" type="submit">Login</button>
</form>

在我的login_push.php页面上,这是PHP:

include 'core/init.php';
logged_in_protect();

$user = $_POST['username'];
$pass = $_POST['password'];

$user = preg_replace("/[^a-z0-9_\s-]/", "", $user);
$user = preg_replace("/[\s-]+/", " ", $user);
$user = preg_replace("/[\s_]/", "-", $user);

if(!empty($_POST)){
    if(isset($user) && isset($pass)) {
        $result = mysqli_query($conn, "SELECT * FROM users WHERE username = '$user'");
        if(mysqli_num_rows($result) == 0) {
            $errors[] = 'The username or password are incorrect.';
        } else {
            $passR = mysqli_query($conn, "SELECT * FROM users WHERE username = '$user'");
            while($row = mysqli_fetch_array($passR)){
                $dbHash = $row['password'];
                if(password_verify($pass, $dbHash)){
                    $activeQ = mysqli_query($conn, "SELECT active FROM users WHERE username = '$user'");
                    while($row = mysqli_fetch_array($activeQ)){
                        $active = $row['active'];
                        if($active == 0){
                            $errors[] = 'This user has not activated their account.';
                        } else {
                            $remember_me = ($_POST['remember_me'] == "on") ? 1 : 0;
                            if(isset($_POST['remember_me']) && $remember_me == 1){
                                $_SESSION['user_log'] = time() + 7889238;
                            } else {
                                $_SESSION['user_logi'] = time() + 3600;
                            }
                            $_SESSION['user_id'] = $user;
                            header('location: ./user');
                        }
                    }
                } else {
                    $errors[] = 'The username or password are incorrect.';
                }
            }
        }
    } else {
        header('location: ./');
    }
}

差不多,我想要的是:

提交表单后,它会将表单中的所有数据推送到login_push.php页面,该页面上的PHP将继续运行。

它将查询数据库并将信息发送回原始页面,如果变量$errors不为空,它将自动在页面上回显它(在form code block的第6行上回显) ,无需刷新页面。但是,如果变量为空,则会将它们记录下来!

感谢所有帮助,

干杯!

编辑:我已经测试了其他代码,但是,它没有按照我希望的方式工作。

1 个答案:

答案 0 :(得分:2)

请勿在您的ajax中使用header('location: ./user');。你有一些重复的代码,比如$result = mysqli_query($conn, "SELECT * FROM users WHERE username = '$user'");你为什么不只调用一次?

您很容易受到mysql注入,因为您没有转义变量。

您从$username设置了$_POST,之后您检查了isset($_POST),为什么会这样?

无论如何,您需要使用errormessage键来回显成功/失败或JSON对象。

$result = [
    'error' => 0,
    'message' => ''
];
//You can do other validations here
if (!empty($_POST)) {

    //Do the dbhash here
    $sql = "SELECT COUNT(*) AS cnt FROM `users` WHERE `username` = '" . mysqli_real_query($conn, $_POST["username"]) . "' AND `password` =  '" . password_verify($_POST['pass'], $dbHash) . "'";
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_row($res);
    if ($row['cnt'] < 1) {
        $result = [
            'error' => 1,
            'message' => 'Bad username or password'
        ];
    }
    //You can add success message if you want
}
echo json_encode($result);

在你的javascript中:

$.ajax({
    type: 'post',
    url: 'login_push.php',
    data: $('#_js_pdTr1').serialize(),
    success: function(response) {
        if (response.error != 0) {
            //Show error here
        } else {
           window.location.href = './user'; //Better to use absolute path here
        }
    }
},'json');