通过AJAX访问时,$_POST中出现未定义的索引错误


Undefined index errors from $_POST when accessing through AJAX

我正在尝试使用ajax来显示从php登录的结果。但这行不通。显示错误未定义的索引如下。

注意:未定义的索引:userEmail inC: 第10行上的''examplep''htdocs''controllers''login.controllers.php

注意:中的未定义索引:userPasswordC: 第10行上的''examplep''htdocs''controllers''login.controllers.php

登录失败

以下是我的源代码:login.views.php

<form id="loginForm" action="/controllers/login.controllers.php" method="post">
    <input id ="userEmail" type="text" name="userEmail" placeholder="Email">
    <input id ="userPassword" type="password" name="userPassword" placeholder="Password">
    <button id ="loginSubmit" type="submit" name="loginSubmit">Login</button>
    <div id="msg"></div>
</form>

login.Controller.php

<?php
    include("../models/user.models.php");
    include("../models/dataBase.models.php");
    $dbc = new dataBase();
    $connect = $dbc->connect('localhost','root','','how_database','','hide');
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $user = new user();
        if ($user->login($connect,$_POST['userEmail'],$_POST['userPassword']) == true){
            echo "Login Successful";
        }
        else {
            echo "Login failed";
        }
    }
    $dbc->close($connect);
?>

loginjax.js

$("#loginSubmit").click(function(){
   if ($("#userEmail").val() == "" || $("userPassword").val() == "") {
       $("div#msg").html("Please enter your email and password");
   }
   else {
       $.post(
           $("#loginForm").attr("action"),
           $("#loginForm:input").serializeArray(),
           function(data){
               $("div#msg").html(data);
           }
       );
   }
   $("#loginForm").submit(function(){
       return false;
   })
});

更新问题:现在我想在点击提交按钮后添加消息"等待",在显示结果消息时隐藏它。我该怎么办?。谢谢

您应该需要在form上调用serialize(),而不是在输入列表上调用serializeArray()。试试这个:

$.post(
    $("#loginForm").attr("action"),
    $("#loginForm").serialize(),
    function(data){
        $("div#msg").html(data);
    }
);

函数之间的区别在于输出的格式。serializeArray()返回一个对象,该对象的格式可能不适合接收端点,serialize()将表单的值转换为查询字符串。

试试这个:

$("#loginSubmit").click(function(){
   if ($("#userEmail").val() == "" || $("userPassword").val() == ""){
       $("div#msg").html("Please enter your email and password");
   }else{
       var formData = new FormData($("#loginSubmit")[0]);
       $.ajax({
          url: $("#loginForm").attr("action"),
          type: 'POST',
          data: formData,
          async: false,
         dataType: "json",
         success: function (data) {
            //here success
          },
         cache: false,
         contentType: false,
         processData: false
         });
   }
   $("#loginForm").submit(function(){
       return false;
   })
});

使用此

$("#loginForm").serialize()

而不是

 $("#loginForm:input").serializeArray()

您必须使用

 $.post(
       $("#loginForm").attr("action"),
       $("#loginForm:input").serialize(),
       function(data){
           $("div#msg").html(data);
       }