首页 > 解决方案 > 使用 jQuery AJAX 向所需的 PHP POST 请求处理程序提交表单不起作用

问题描述

每当我从使用 jquery ajax 向 PHP api 提交表单时,表单都不会提交到所需的发布请求处理程序。但是当我基本上提交表单时,我的意思是不使用 javascript 或 jquery 提交表单并且它重定向到带有 json 响应的 php 页面。

注意这里的 CORS 没有问题,因为我在 api 中允许跨站点请求,所以 CORS 很好。

下面是我的login.html文件。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./assets/css/style.css">
    <script src="./assets/js/jquery-3.4.1.min.js"></script>
    <title>User Login Page</title>
</head>

<body>
    <div class="header">
        <h2>Login</h2>
    </div>

    <form action="http://localhost/auth-app/server.php" method="post">
        <div class="input-group">
            <label for="">Email</label>
            <input type="email" name="email" id="email" required>
        </div>
        <div class="input-group">
            <label for="">Password</label>
            <input type="password" name="password" id="password" required>
        </div>
        <div class="input-group">
            <input type="submit" value="Login" name="login" class="submit-btn">
        </div>
        <p>
            Not yet a member? <a href="register.html">Register</a>
        </p>
    </form>

    <script>
        $(document).ready(function () {
            // submit login form with ajax
            $('form').submit(function (event) {
                /* stop form from submitting normally */
                event.preventDefault();
                $(".submit-btn").click(function () {
                    $.post("http://localhost/auth-app/server.php", {
                        email: $('#email').val(),
                        password: $('#password').val()
                    },
                        function (data, status) {
                            const json = $.parseJSON(data);
                            console.log("Data: " + typeof(json) + "\nStatus: " + status);
                        });
                });
            });
        });


    </script>
</body>

</html>

注意我想要的是能够使用 jquery ajax将表单提交到所需的 PHP 发布请求处理程序函数。

下面是我的server.php api 文件。


$errors = array();

// login
if (isset($_POST['login'])) {
    $email = $db->real_escape_string($_POST['email']);
    $password = $db->real_escape_string($_POST['password']);

    if (empty($email)) {
        array_push($errors, 'Email is required');
    }
    if (empty($password)) {
        array_push($errors, 'Password is required');
    }

    if (count($errors) == 0) {

                // log user in
                $data = ['success_login' => 'true'];
                header('Content-type: application/json');
                echo json_encode(null);
        } else {
            array_push($errors, 'The email or password is incorrect');
            // after entering wrong credentials
            $data = ['success_login' => 'false'];
            header('Content-type: application/json');
            echo json_encode($data);
        }
}

调试控制台中,我收到以下错误。 请注意,这只是证明 post 请求没有到达 api 文件中的 php post request 处理程序。

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

我期望在控制台中得到的是 json 数据,如下所示:

success_login   "true"

!重要信息: 我对 php 不是很有经验,但我注意到在不使用任何 javascript(例如 jquery 或 ajax)提交表单时,表单会成功提交,因为提交按钮的名称(例如<input type="submit" value="Login" name="login">)与里面的名称相同$_POST['login']。但是在技术上使用 ajax 提交表单时,您不使用该按钮提交。

那么我该如何解决这个问题呢?谢谢你用爱发帖。

标签: javascriptphpjqueryhtmlajax

解决方案


尝试类似下面的代码

      $(document).ready(function () {
        $('form').submit(function (event) {
        event.preventDefault();
        $(".submit-btn").click(function () {

         name: $('#email').val(),
         password: $('#password').val()

        $.ajax({
            type: 'post',
            url: 'http://localhost/auth-app/server.php',
            data: {
                name: name,
                password : password,
                action: 'login'
            },
            success: function(response) {

            }
        })
    });
    });
    });

推荐阅读