简体   繁体   English

使用 jQuery AJAX 提交表单到所需的 PHP POST 请求处理程序不起作用

[英]Submitting Form with jQuery AJAX to the required PHP POST request handler is not working

Whenever I submit a from using jquery ajax to an PHP api the form is not submitting to the required post request handler .每当我使用 jquery ajax 向 PHP api 提交表单时,表单不会提交到所需的post 请求处理程序 But when I submit the form basically, I mean without using an javascript or jquery the form is submit and it is redirecting to a php page with json response.但是,当我基本上提交表单时,我的意思是不使用 javascript 或 jquery 提交表单,并且它重定向到带有 json 响应的 php 页面。

Note No problems with CORS here the CORS are fine as I have allowed cross-site requests in the api.注意这里的 CORS 没有问题 CORS 很好,因为我允许 api 中的跨站点请求。

Below is my login.html file.下面是我的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>

Note What I want is to be able to submit the form to the required PHP post request handler function using jquery ajax.注意我想要的是能够使用 jquery ajax 将表单提交到所需的 PHP 发布请求处理程序函数

Below is my server.php api file.下面是我的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);
        }
}

In debug console I'm getting the error bellow.调试控制台中,我收到以下错误。 Note this is just proof that the post request is not reaching the php post request handler in the in the api file.请注意,这只是证明 post 请求没有到达 api 文件中的 php post 请求处理程序。

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

What I'm expecting to get in the console is json data like below:我期望在控制台中得到的是 json 数据,如下所示:

success_login   "true"

!IMPORTANT INFO: I'm not very experienced with php but I have noticed that when submitting form without using any javascript eg jquery or ajax the form submits successfully because the name of the submit button eg <input type="submit" value="Login" name="login"> is the same as the name inside $_POST['login'] . !重要信息:我对 php 不是很有经验,但我注意到当不使用任何 javascript(例如 jquery 或 ajax)提交表单时,表单成功提交,因为提交按钮的名称,例如<input type="submit" value="Login" name="login">$_POST['login']的名称相同。 But when submitting form using ajax technically you don't use that button to submit.但是在技术上使用 ajax 提交表单时,您不使用该按钮提交。

So how do I solve this problem?那么我该如何解决这个问题呢? Thank you posted with Love.谢谢你用爱发帖。

Try something like below code尝试类似下面的代码

      $(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) {

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

You do not need to declare the click button event as you are already using the form submit button event.您不需要声明单击按钮事件,因为您已经在使用表单提交按钮事件。 Also, add the login key as the parameter value in $.post , as you are checking it's isset value in login.php file.此外,在$.post 中添加登录键作为参数值,因为您正在检查login.php文件中的 isset 值。

Also, note that there is extra closes braces "}" in your login.php file另外,请注意在login.php文件中有额外的大括号“}”

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

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