简体   繁体   English

发送数据而无需重新加载页面PHP Ajax

[英]Send Data Without Reloading Page PHP Ajax

I am attempting to create a login page, in which, every attempt at a login is done on the page, straight away; 我正在尝试创建一个登录页面,在该页面中,每次登录的尝试都直接在该页面上完成; rather than refreshing the page. 而不是刷新页面。 Something along the lines of how Google do their login page, and how Facebook submit messages without refresh. Google如何处理其登录页面以及Facebook如何不刷新地提交消息。

I have programmed the backend functionality of the page in PHP and now I would like to give it that little more to make it look and function exceptionally. 我已经用PHP对页面的后端功能进行了编程,现在我想给它更多一点,以使其具有特殊的外观和功能。

This is the current Ajax script I am using which doesn't want to work the way I would like it to (I have tried multiple others with the same results): 这是我正在使用的当前Ajax脚本,它不希望以我想要的方式工作(我已经尝试了多个其他具有相同结果的脚本):

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

            e.preventDefault();

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

This is the form for the page: 这是页面的形式:

<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>

and on my login_push.php page, this is the PHP: 在我的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: ./');
    }
}

Pretty much, what I would like is: 差不多,我想要的是:

When the form is submitted, it will push all the data from the form to the login_push.php page, and the PHP on that page will continue to run. 提交表单后,它将所有数据从表单推送到login_push.php页面, login_push.php面上的PHP将继续运行。

It will query the database and send information back to the original page and if the variable $errors is not empty, it will automatically echo it on the page (echoed on line 6 of the form code block ), without refreshing the page. 它将查询数据库并将信息发送回原始页面,如果变量$errors不为空,它将自动在页面上回显它(在form code block的第6行中回显),而无需刷新页面。 However, if the variable is empty, it will log them in! 但是,如果变量为空,则将其登录!

All help is appreciated, 感谢所有帮助,

Cheers! 干杯!

EDIT: I have already tested the other code out, however, It did not work the way I would like it to. 编辑:我已经测试了其他代码,但是,它没有按照我想要的方式工作。

Do not use header('location: ./user'); 不要使用header('location: ./user'); in your ajax. 在你的ajax中。 You have some duplicated code, like $result = mysqli_query($conn, "SELECT * FROM users WHERE username = '$user'"); 您有一些重复的代码,例如$result = mysqli_query($conn, "SELECT * FROM users WHERE username = '$user'"); Why do not you call it only once? 为什么不只调用一次?

You are vulnerable to mysql injection, because you do not escape your variables. 您很容易受到mysql注入的攻击,因为您无法逃避变量。

You are set the $username from $_POST and after that you've checked ths isset($_POST) , why is it? $_POST设置$username ,然后检查isset($_POST) ,为什么呢?

Anyway, you need to echo a success / failed, or a JSON object with error and message keys. 无论如何,您都需要回显成功/失败或带有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);

And in your javascript: 在您的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');

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

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