对PHP的jQuery AJAX POST请求必须提交两次才能工作

时间:2018-07-09 20:03:25

标签: javascript php jquery ajax forms

我们正在构建一个基本的登录表单,该表单将根据用户凭据重定向到不同的页面。

由于某种原因,除非我们两次提交相同的信息(第一次,它会将所有内容都扔到URL中,就像GET一样),否则我们无法获取登录表单来返回员工类型的值并重定向到正确的页面。请求,除了它将请求写到URL之前,甚至包括“#”)。

我们正在使用Vue.js,但我不知道它与当前问题确实相关,只是它意味着HTML和JS在同一个“组件”文件中。

HTML:

<form class="login-form" id="loginform">
   <div class="form-group space">
      <label class="float-label" for="username">Username</label>
      <input type="username" name="username" id="username" class="form-control" >
   </div>
   <div class="form-group">
      <label class="float-label" for="username">Password</label>
      <input type="password" name="password" id="password" class="form-control" >
   </div>
   <div class="form-group"> 
      <button type="submit" class="btn btn-primary float-right" id="login">Log in</button>
   </div>
</form>

JS:

$(function () {
   $("#loginform").on('submit', function (e) {
       e.preventDefault();
       console.log($('#loginform').serialize());
       $.ajax({
            type: 'post',
            url: 'https://fleetr-208415.appspot.com/',
            data: $(this).serialize(),
            cache: false,
            success: function (data) {
                var employeeId = data;
                console.log(employeeId);
                    if (employeeId == 1)
                {
                        adminScreen();
                }
                else if (employeeId == 2)
                {
                        dispatcherScreen();
                }
                else if (employeeId == 3)
                {
                        truckerScreen();
                }
                else
                {
                    alert("error");
                }
            }
        });
    });

})        

function truckerScreen()
{
        // similar behavior as an HTTP redirect
    window.location.replace("/#/trucker");
}

function dispatcherScreen()
{
        window.location.replace("/#/dispatch");
}

function adminScreen()
{
        window.location.replace("/#/admin");
}

PHP:

<?php header(“Access-Control-Allow-Origin: *“);
require ‘connection.php’;
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$result = mysqli_query($conn, ‘select name, email, employee_type from employee where employee_id=“‘.$username.‘” and password=“‘.$password.‘“’);
if(mysqli_num_rows($result)==1)
{
    while ($row = $result->fetch_assoc())
    {
        $name = $row[“name”];
        $email = $row[“email”];
        $employee_type = $row[“employee_type”];
    }
    echo $employee_type;
}
?>

因此,如果您要提交用户名:James和密码:123,则首次提交时,网址将变为

  

www.blahblah.net/?username=James&password=123#/登录

然后,在重新提交相同的信息后,您将被重定向到正确的页面。请注意,仅使用表单信息重新加载URL不会产生相同的效果。

我们俩都没有使用PHP或AJAX进行表单提交/用户验证的经验,而对于为什么发生这种奇怪的错误,我们完全不知所措。

0 个答案:

没有答案
相关问题