首页 > 解决方案 > 登录表单,Ajax 调用 PHP 函数

问题描述

我有一个登录表单,我想通过 Ajax 将其中的数据传递到另一个文件中的 PHP 函数中。这样做的目的是我希望页面在用户登录时不重新加载。

现在,当用户尝试登录时没有任何反应。似乎 access.php 没有处理从 Ajax 发送的数据。

有人可以告诉我为什么这不起作用吗?可能的原因是什么?

索引.html:

      <div class="login-form">
      <form method="post" action="index.php">
          <input id="username" type="text" placeholder="Username...">
          <input id="password" type="password" placeholder="Password...">
          <button id="button" type="submit">Login</button>
      </form>

      <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
      <script type="text/javascript">
      $('#button').click(function(e) {
          e.preventDefault();
          var username = $('#username').val();
          var password = $('#password').val();
          $.ajax({
              type: 'POST',
              url: 'resources/includes/access.php',
              data: {
                func: 'loginSubmit',
                usernamePHP: username,
                passwordPHP: password
               },
              success: function(response) {
                  $('#result').html(response);
              }
          });
      });
      </script>
  </div>

访问.php:

function loginSubmit(){
  require '../dbh.inc.php';
  $mailuid = $_POST['usernamePHP'];
  $password = $_POST['passwordPHP'];
  if(empty($mailuid) || empty($password)){
    header("Location: ../../index.php?error=emptyfields");
    exit();
  }
  else{
    $sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
    $stmt = mysqli_stmt_init($conn);
    if(!mysqli_stmt_prepare($stmt, $sql)){
      header("Location: ../../index.php?error=sqlerror");
      exit();
    }
    else{
      mysqli_stmt_bind_param($stmt, "ss", $mailuid, $password);
      mysqli_stmt_execute($stmt);
      $result = mysqli_stmt_get_result($stmt);
      if($row = mysqli_fetch_assoc($result)){
        $pwdcheck = password_verify($password, $row['pwdUsers']);
        if($pwdcheck == false) {
          header("Location: ../../index.php");
          exit();
        }
        else if($pwdcheck == true) {
          session_start();
          $_SESSION['userId'] = $row['idUsers'];
          $_SESSION['userUid'] = $row['uidUsers'];
          header("Location: ../../index.php?login=success");
          exit();
        }
        else{
          header("Location: ../../index.php");
          exit();
        }
      }
    }
  }
}

标签: javascriptphphtmlajax

解决方案


从我从文档中可以看出,将函数名称添加为数据属性不会调用该函数;

数据类型:PlainObject 或 String 或 Array

当您调用 access.php 时,该文件仅包含一个函数定义,您实际上并没有调用它。

所以你有两个选择。通过在函数后添加loginSubmit()(在 access.php 末尾)来调用函数,或者从函数中完全删除 access.php 上的代码。


推荐阅读