首页 > 解决方案 > 使用 $.ajax 向服务器请求不返回成功 - PHP

问题描述

我正在尝试使用 jQuery 和 ajax 向服务器发出请求并使用 PHP 处理请求,但是,每次服务器使用我在 PHP 文件中指定的“404”(在控制台中:发生错误!)代码进行响应时. 问题是即使使用正确的用户名和密码,请求仍然不会返回代码 200(成功)。HTML 文件名为 login.php ,JS 文件名为 main-2.js ,处理请求的文件是 login-process.php 这是我的 HTML 代码:

$(document).ready(() => {
  $('#awesome-login-form').submit((event) => {
    event.preventDefault();
    const data = $('#awesome-login-form').serialize();
    const adminUserName = $('#login-user-name').val();
    const adminPassword = $('#login-password').val();

    $('#usr-err-msg').html('');
    $('#psw-err-msg').html('');
    $('#total-err-msg').html('');

    $.ajax({
      type: "POST",
      url: "login-process.php",
      dataType: "json",
      data: data,
      success: (data) => {
        if (data.code === '200') {
          console.log('It works!');
          window.location.href = 'dashboard-index.php';
        } else if (data.code === '404') {
          console.log('Error occurred!');
          $('#usr-err-msg').innerText = data.nameErrMsg;
          $('#psw-err-msg').innerText = data.passwordErrMsg;
          $('#total-err-msg').innerText = data.totalError;
        }
      }
    });
  });
});
<!doctype html>
<html lang="en">

<head>
  <title>IPConcrete | Admin-Login</title>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" type="text/css" href="css/login-custom-style.css">
  <link rel="stylesheet" type="text/css" href="vendor/my-grid.css">
  <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto&display=swap">

  <link rel="stylesheet" type="text/css" href="css/my-style.css">


</head>

<body>

  <h2 style="text-align:center;color:#ff5e15;margin-top:50px;">IPCONCRETE</h2>

  <div class="log-form">
    <h2 style="color:#ff5e15;font-weight:800;">Login to your account</h2>


    <form method="post" action="login.php" id="awesome-login-form">
      <input type="text" name="admin_name" title="username" placeholder="username" id="login-user-name" />
      <p id="usr-err-msg" style="display:inline-block;"></p>

      <input type="password" name="admin_password" title="username" placeholder="password" id="login-password" />
      <p id="psw-err-msg" style="display:inline-block;"></p>

      <button type="submit" name="login_btn" class="btn" id="login-submit">Login</button>
      <p id="total-err-msg" style="display:inline-block;"></p>

      <a class="forgot" href="#">Forgot Username?</a>
    </form>


  </div>
  <!--end log form -->

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="js/main-2.js"></script>

</body>

</html>

PHP文件代码是:


<?php
require_once('functions.php');
require_once('config.php');



$nameErrMsg = '';
$passwordErrMsg = '';
$totalError = '';
$_SESSION['isAdmin'] = false;

$adminName = $_POST['admin_name'];
$adminPassword = $_POST['admin_password'];
$errorStatus = false;

if (checkEmpty($adminName)) {
   $errorStatus = true;
   $nameErrMsg = 'The user name field is empty!';
}

if (checkEmpty($adminPassword)) {
   $errorStatus = true;
   $passwordErrMsg = 'The password field is empty!';
}

if (!(checkEmpty($adminName)) && !(checkEmpty($adminPassword))) {


   $sqlCommand = "SELECT FROM `io9mp_admins` WHERE `user_name` = ? AND `password` = ?";

   $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
   $sqlCommandPrepare->execute([

       $adminName,
       $adminPassword

   ]);

   //Checking if the user input values are equal to the data base fields...
   $result = $sqlCommandPrepare->fetch();

   if (mysqli_num_rows($result) === 1) {
       $errorStatus = false;
   } else if (mysqli_num_rows($result) !== 1) {
       $errorStatus = true;
   }


}


if ($errorStatus === true) {
   echo json_encode([
       'code' => '404', 'totalError' => $totalError, 'nameErrMsg' => $nameErrMsg, 'passwordErrMsg' => $passwordErrMsg
   ], JSON_THROW_ON_ERROR, 512);
}

else if ($errorStatus === false) {

   echo json_encode([
       'code' => '200',
   ], JSON_THROW_ON_ERROR, 512);
}

checkEmpty() 函数在functions.php中:

<?php
function checkEmpty($input){
    return empty( trim($input) );
}

标签: javascriptphpjqueryajax

解决方案


mysqli_XXX使用 PDO 时不能使用函数。改变:

   if (mysqli_num_rows($result) === 1) {
       $errorStatus = false;
   } else if (mysqli_num_rows($result) !== 1) {
       $errorStatus = true;
   }

    $errorStatus = !$result;

推荐阅读