简体   繁体   English

如何检索PHP中Ajax发送的数据?

[英]How to retrieve data that is sent by ajax in php?

I am still a student and I am really new to web development. 我仍然是一名学生,对Web开发真的很陌生。 I am currently learning ajax. 我目前正在学习ajax。 I wanted to pass (via button) an ID to my PHP script for SQL processing, and display the data retrieved to my page without reloading it. 我想(通过按钮)将一个ID传递给我的PHP脚本以进行SQL处理,并显示检索到我的页面的数据而无需重新加载它。 But it doesn't seem to work. 但这似乎不起作用。 After I press the button, it visually loads the PHP page (which, in my own understanding, wasn't suppose to happen when using ajax). 在按下按钮后,它会以可视方式加载PHP页面(据我个人理解,使用ajax不会发生该页面)。

HTML and JavaScript code: HTML和JavaScript代码:

<!DOCTYPE HTML>
<html>

<head>

</head>
<body>

<?php
  session_start();
?>
<form action="retrieve_data.php" method="POST" name="searchForm">
    EMPLOYEE ID: <input type="text" name='emp_id' id='emp_id'/>
    <input type="submit" value="Search" onsubmit="searchEmp()"/>
</form>
    <br>
    NAME:<p id="empName"></p><br>
    POSITION:<p id="empPos"></p>

 <script>

 function searchEmp() {

            var empID = document.getElementById('emp_id').value;
            var query = "?emp_id = " + empID;
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {

           if(xhr.readyState == 4) {
              document.getElementById('empName').innerHTML = '<?php echo  $_SESSION["empName"]; ?>';
              document.getElementById('empPos').innerHTML = '<?php echo  $_SESSION["empPosition"];?>';

           }
        }

            xhr.open("GET", "retrieve_data.php" +query, true);

            xhr.send(null);

        };
    </script>

retrieve_data.php: retrieve_data.php:

    <?php

session_start();
if(!empty($_GET["emp_id"])){

$_SESSION["emp_id"] = $_GET["emp_id"];
$emp_id = $_SESSION["emp_id"];

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "overtimedtr";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM employees where id ='".$emp_id."'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {

        $_SESSION["empName"] = $row['name'];
        $_SESSION["empPosition"] = $row['position'];

    }
} else {
    echo "0 results";
}

mysqli_close($conn);
}

?>

Here's a picture of my html page: 这是我的html页面的图片:

我的html页面的图片

What I am trying to do is when I click the search button, the page should display the name and the position without reloading the page in a <p> element whose id's are "empName" and "empPos", the outcome isn't what i wanted, it displays my PHP page instead (which displays empty). 我想做的是,当我单击搜索按钮时,页面应显示名称和位置,而无需在ID为“ empName”和“ empPos”的<p>元素中重新加载页面,结果不是我想要,它显示了我的PHP页面(显示为空)。

EDIT: 编辑:

I have discovered that I don't need to add method="GET" in the form, then the page did not have to refresh, just as what I have wanted. 我发现我不需要在表单中添加method="GET" ,然后页面就不必刷新,就像我想要的那样。

<form name="searchForm">
        EMPLOYEE ID: <input type="text" name='emp_id' id='emp_id'/>
        <input type="submit" value="Search" onsubmit="searchEmp()"/>
</form>

The only remaining problem is that I could not seem to get the value of $_SESSION["empName"] and $_SESSION["empPosition"] from my PHP page. 剩下的唯一问题是,我似乎无法从我的PHP页面获得$_SESSION["empName"]$_SESSION["empPosition"] What could I have been getting wrong? 我可能出了什么问题?

if(xhr.readyState == 4) {
              document.getElementById('empName').innerHTML = '<?php echo  $_SESSION["empName"]; ?>';
              document.getElementById('empPos').innerHTML = '<?php echo  $_SESSION["empPosition"];?>';

           }

You have many errors in your code. 您的代码中有很多错误。

Errors in your retrieve_data.php 您的retrieve_data.php中的错误

When you use AJAX, you don't use $_SESSION to exchange data; 当您使用AJAX时,您无需使用$_SESSION来交换数据。 instead, you print the results like in a normal page but usually embeeded in a structured format like JSON or XML . 相反,您可以像在普通页面中那样打印结果,但通常以JSONXML之类的结构化格式嵌入。 What I recommend you is to organize everything that you are going to retrieve in an array and then use a coding function like json_encode .For example: 我建议您将要检索的所有内容组织成一个数组,然后使用json_encode这样的编码函数。例如:

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $result["empName"] = $row['name'];
        $result["empPosition"] = $row['position'];
    }
} else {
    $result["empName"] = '0 results.';
    $result["empPosition"] = '0 results.';
}
//json encode prints the result formatted
exit(json_encode($result));

Errors in your html HTML中的错误

First of all, when you use AJAX, you usually don't use forms, because the default behaviour of a form is to load the page; 首先,在使用AJAX时, 通常 使用表单,因为表单的默认行为是加载页面。 also the info of method and action is already beeing given in the open() method so you are beeing redundant(Also notice that you are telling the form to use POST while AJAX to use GET). 同样,方法和操作的信息已经在open()方法中给出,因此您会感到多余(还请注意,您告诉表单使用POST,而AJAX使用GET)。 Better use a button. 最好使用一个按钮。 If you have to use use forms, then always return false to prevent the page being loaded. 如果必须使用使用表单,则始终返回false以防止页面被加载。 Also, inside the onreadystatechange you must NOT use php's echo . 另外,在onreadystatechange内部,您不得使用php的echo Remember that PHP is a preprocesor and once in the client side everything printed is inalterable. 请记住,PHP是前置处理器,一旦在客户端,所有打印的内容就无法更改。 You must to use the XMLHttpRequest properties responseText or responseXML. 您必须使用XMLHttpRequest属性responseText或responseXML。 This properties contain the response received. 此属性包含收到的响应。 If you follow my recommendation of using json_encode in you php file, then tou need to use JSON.parse to process the data received. 如果您遵循我在php文件中使用json_encode建议,则您需要使用JSON.parse来处理接收到的数据。 Also in your query string don't use spaces So for example: 另外,在查询字符串中不要使用空格,例如:

EMPLOYEE ID: <input type="text" name='emp_id' id='emp_id'/>
<button onclick="searchEmp()">Search</button>
<br>
NAME:<p id="empName"></p><br>
POSITION:<p id="empPos"></p>

<script>

    function searchEmp() {
        var empID = document.getElementById('emp_id').value;
        var query = "?emp_id=" + empID;
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                jsonResponse = JSON.parse(xhr.responseText);
                document.getElementById('empName').innerHTML = jsonResponse.empName;
                document.getElementById('empPos').innerHTML = jsonResponse.empPosition;
            }
        }

        xhr.open("GET", "retrieve_data.php" + query, true);
        xhr.send(null);
    }
</script>

I recommend you to check basic AJAX documentation, because it seems that you have some confusion in some AJAX concepts. 我建议您检查基本的AJAX文档,因为您似乎对某些AJAX概念有些困惑。

https://www.w3schools.com/xml/ajax_intro.asp https://www.w3schools.com/xml/ajax_intro.asp

Let me know if you have any more questions. 如果您还有其他问题,请告诉我。

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

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