Home » Php » javascript – Request to server with $.ajax doesn't return success – PHP

javascript – Request to server with $.ajax doesn't return success – PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to make a request to server on a with jQuery and ajax and process the request with PHP , however , every time the server responds with ‘404’ (in console: Error occurred!) code that I specified in the PHP file.
The problem is that even with the correct username and password , still the request wouldn’t return as code 200 (successful).
HTML file is named login.php , JS file is named main-2.js and the file that process the request is login-process.php This is my HTML code :

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

and the PHP file code is:


<?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);
}

the checkEmpty() funtion is in functions.php:

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

How to&Answers:

You can’t use mysqli_XXX functions when you’re using PDO. Change:

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

to

    $errorStatus = !$result;