我在未使用ajax重新加载的情况下提交表单时遇到问题

问题描述 投票:0回答:1

我的代码有一些问题。当我输入正确的用户名和密码时,它无法重定向到index.php。

我想使用 window.location.href 进行 php 文件侧导航而不是 js 侧导航

登录.php:

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['btn-login'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];


        if (User::authenticate($conn, $username, $password)) {
            // Thực hiện sesison
            Auth::login();
            // redirect("index.php");
            echo "success";
            header("Location: index.php");
        } else {
            echo "<script>alert('Vui lòng đăng nhập lại');</script>";
        }
    }
    ?>

main.js:

   $("form").on("submit", function (event) {
        event.preventDefault(); // Prevent the form from being submitted normally

        if (validateLoginForm()) {
            // Use AJAX to submit the form
            $.ajax({
                url: "login.php", // URL to the PHP file that will handle the AJAX request
                type: "POST",
                data: $(this).serialize(), // Serialize form data for submission
                success: function (response) {
                    // Handle success
                    if (response === "success") {
                        window.location.href = "login.php";
                    } else {
                        alert("Login failed. Please try again."); // Show error message
                    }
                },
                error: function (error) {
                    // Handle error
                    alert("An error occurred. Please try again."); // Show error message
                },
            });
        }
    });

谢谢您的帮助<3

javascript jquery ajax
1个回答
-1
投票

我对标题和你的帖子有点困惑,你想用 JS 还是 PHP 来做到这一点?在我看来这是一个复杂的问题

© www.soinside.com 2019 - 2024. All rights reserved.