简体   繁体   English

AJAX 调用通过 POST 发送数据,但 PHP 不接收

[英]AJAX call sends data via POST, but PHP doesn't receive

So, I have this really weird problem.所以,我有这个非常奇怪的问题。 I have constructed a web application with a login form on my home pc, but when I try to migrate it to a server with domain, php went all crazy and everything doesn't work anymore now.我在我的家用电脑上构建了一个带有登录表单的 Web 应用程序,但是当我尝试将它迁移到带有域的服务器时,php 变得非常疯狂,现在一切都不再起作用了。

So I have a login form, which sends the data via an AJAX POST call to a php file, which compares the given data to the interface.所以我有一个登录表单,它通过 AJAX POST 调用将数据发送到一个 php 文件,该文件将给定的数据与接口进行比较。 But it seems that in one way or another, the data isn't getting received by the php.但似乎以某种方式,数据没有被 php.ini 接收。 Let me show you what my setup is:让我告诉你我的设置是什么:

the Javascript: Javascript:

    console.log(username);
    $.ajax({
        url: "server/login_server.php",
        type: "POST",
        datatype: "JSON",
        data: {username: username, password: password},
        complete: function(data) {
            console.log(data.responseText);

            if(data.responseText == "SUCCESS") {
                location.assign("pages/overview.html");
            }else if(data.responseText == "ERROR_CONNECT") {
                showError("kan niet verbinden met server");
            }else if(data.responseText == "ERROR_CODE") {
                showError("Er is iets misgelopen...");
            }else if(data.responseText == "ERROR_FALSE") {
                showError("Inloggegevens ongeldig");
            }else if(data.responseText == "ERROR_MULTIPLE") {
                showError("Er zijn meerdere resultaten gevonden");
            }else if(data.responseText == "ERROR_FORBIDDEN") {
                showError("Dit account heeft geen admin-privileges");
            }

            $("#login_password").val("");
        },
        error: function(data) {
            console.log(data);
        }
    });

Some lines are written in dutch, but don't worry, it doesn't say anything important.有些台词是用荷兰语写的,但别担心,它没有说任何重要的东西。 The console (on line 1) clearly writes the username, so I know that the username value isn't empty.控制台(在第 1 行)清楚地写了用户名,所以我知道用户名值不为空。

The PHP file: PHP文件:

<?php
session_start();

$config = include('config.php');

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

$conn = new mysqli($config['db_host'], $config['db_user'],      $config['db_password'], $config['db_name']);

$result = "SUCCESS";

if($conn->connect_error) {
    $result = $conn->connect_error;
    die($result);
}

$sql = "SELECT * FROM users WHERE userName='".$username."'";
$status = mysqli_query($conn, $sql);

if(!$status) {
    $result = "ERROR_CODE";
    die($result);
}

$num_rows = mysqli_num_rows($status);
$row = mysqli_fetch_array($status);

if($num_rows == 0) {
    $result = "ERROR_FALSE";
    die($username);
}else if($num_rows > 1) {
    $result = "ERROR_MULTIPLE";
    die($result);
}else{
    if($row['isAdmin'] == "false") {
        $result = "ERROR_FORBIDDEN";
        die($result);
    }else{
        $_SESSION['logedIn'] = "true";
        $result = "SUCCESS";
        die($result);
    }
}

echo $username;
?>

It is a simplistic representation of what I am trying to do, but this is where it goes wrong.这是我正在尝试做的事情的简单表示,但这就是出错的地方。 It gets the username from the post call, and gives it back as data.responsetext to the javascript file.它从 post 调用中获取用户名,并将其作为 data.responsetext 返回给 javascript 文件。

The javascript file in its turn, prints out an empty string as the result of the php file. javascript 文件依次打印出一个空字符串作为 php 文件的结果。

Firebug log:萤火虫日志:

萤火虫日志

Adding the full error log gives me the following:添加完整的错误日志给了我以下内容:

"<br />
<b>Notice</b>:  Undefined variable: conn in    <b>/home/netwerklevensein/public_html/dagboek/server/login_server.php</b> on   line <b>8</b><br />
<br />
 <b>Warning</b>:  mysql_real_escape_string() expects parameter 2 to be resource,    string given in    <b>/home/netwerklevensein/public_html/dagboek/server/login_server.php</b> on    line <b>8</b><br />
<br />
<b>Notice</b>:  Undefined variable: conn in    <b>/home/netwerklevensein/public_html/dagboek/server/login_server.php</b> on   line <b>9</b><br />
<br />
<b>Warning</b>:  mysql_real_escape_string() expects parameter 2 to be resource,    string given in <b>/home/netwerklevensein/public_html/dagboek/server/login_server.php</b> on line <b>9</b><br />
" 

I hope you guys can help me.我希望你们能帮助我。

You're mixing MySQL APIs here with (connecting with mysqli_ then using mysql_ escape functions).您在此处混合 MySQL API(使用 mysqli_ 连接,然后使用 mysql_ 转义函数)。

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

that should read as应该读作

$username = mysqli_real_escape_string($conn,$_POST['username']);
$password = mysqli_real_escape_string($conn,$_POST['password']);

Those different APIs do NOT intermix.这些不同的 API 不会混合使用。

Add error reporting to the top of your file(s) which will help find errors.错误报告添加到文件顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.旁注:显示错误只应在暂存时进行,而不要在生产中进行。

Check for errors against your query also:还根据您的查询检查错误:

$status = mysqli_query($conn, $sql) or die(mysqli_error($conn));

You can print你可以打印

echo json_encode(array('username' => $username2));

cause, you set output format is JSON.因为,您设置的输出格式是 JSON。 Another thing, you can use success handler on ajax request, and use only response message (not all XMLHttpRequest response)另一件事,您可以在 ajax 请求上使用成功处理程序,并且仅使用响应消息(并非所有 XMLHttpRequest 响应)

I am not a php expert but looks like you are missing some thing on Ajax calls.我不是 php 专家,但看起来您在 Ajax 调用中遗漏了一些东西。

Here are my suggestions: To post Json you need to stringify using JSON.stringify(data) Also dont forget to set processdata option to false.以下是我的建议:要发布 Json,您需要使用 JSON.stringify(data) 进行字符串化另外不要忘记将 processdata 选项设置为 false。

Please place the blow lines inside your ajax call after data: {username: username, password: password},请在 data: {username: username, password: password} 之后的 ajax 调用中放置吹线,

data: JSON.stringify(data), processData: false,数据: JSON.stringify(data), processData: false,

try this in php,在 php 中试试这个,

echo json_encode(
     array('responseText' => $result)
);

You are trying to access responseText property from data object.您正在尝试从数据对象访问responseText属性。 And echo only $username string并且只回显$username字符串

I see in your AJAX code that you said you are receiving JSON data, but in the php file you just issued an echo or die and that ain't JSON data but plain text.我在你的 AJAX 代码中看到你说你正在接收 JSON 数据,但在 php 文件中你只是发出了一个 echo 或 die 并且这不是 JSON 数据而是纯文本。 So try to put datatype: "text" on the AJAX code.所以尝试将datatype: "text"放在 AJAX 代码上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM