php - 如何使用 Ajax 根据另一个文本框的值填充表单输入文本框

标签 php jquery html mysql ajax

我正在学习 php、html 和 ajax。我已经建立了一个包含员工信息的 MySQL 数据库。我已经设法弄清楚如何使用 ajax 自动填充文本框(称为“员工详细信息”)。当您开始输入员工的姓名时,它将填充他们的全名和公司名称的串联。

我现在要做的是根据第一个文本框的值自动用员工 ID 填充第二个文本框。

我搜索了很多问题和教程,但我找不到如何执行此操作的简单解释,并且我找到的示例不完全包含 php、ajax、html,我无法弄清楚如何将它们拼凑在一起(我不完全是一个编码天才,我无法让任何示例发挥作用)。我已经在这个问题上坚持了好几个小时了,失去了生存的意志!

如果有人能用 php、ajax 和 html 的示例在一个地方帮助我进行简单的解释,我将非常感激!

这是到目前为止我的代码。

form.php

<link rel="stylesheet"        href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<script>
$(function() {
    $( "#employeedetails" ).autocomplete({
        source: 'search.php'
    });
});
</script>

<div class="form-group">
<b class="text-primary">Employee details:</b>
<input type="text" class="form-control" value="" id="employeedetails" name="employeedetails" required>

<b class="text-primary">Id:</b>
<input type="text" name="employeeid" id="employeeid" placeholder="employeeid"/>
</div>

搜索.php

include 'dbconnect.php';

    //get search term
    $searchTerm = $_GET['term'];

    //get matched data from employee table
    $query = $conn->query("SELECT * 
                         FROM employees 
                         WHERE (firstname LIKE '%".$searchTerm."%')
                            OR (surname LIKE '%".$searchTerm."%')
                            OR (companyname LIKE '%".$searchTerm."%')
                         ORDER BY firstname ASC

                        ");
    while ($row = $query->fetch_assoc()) {
        $data[] = $row['firstname'] . " " . $row['surname'] . " - " .     

    }

    //return json data
    echo json_encode($data);
?>

最佳答案

假设您的 HTML 员工详细信息文本框有 id="employeeDetail"并且您的 HTML 员工 ID 文本框有 id="employeeId"您可以使用 jQuery 监听员工详细信息的选择,然后通过 Ajax 发送该选择,并使用用于更新员工 ID 文本框值的 Ajax 响应。这将涉及以下 jQuery 和 PHP 代码:

jQuery 代码:

    $(document).ready(function(){
        $(#employeeDetail).on("change", function(){ //use an appropriate event handler here
             $.ajax({
                 method: "POST",
                 url: "getEmployeeId.php",
                 data: {
                    employee_detail: $("#employeeDetail").val(),
                 },
                 success: function(response){
                    if (response == "FALSE") {
                        var message = "ERROR: something went wrong on the MYSQL side";
                        alert(message);
                    } else {
                        $("#employeeId").val(response);
                    }
                 },
                 error: function(jqXHR, textStatus, errorThrown){
                    var message: "ERROR: something went wrong with the AJAX call - " + textStatus + " - " + errorThrown;
                    alert(message);
                 }
              });
         });
    });

PHP 代码 (getEmployeeId.php):

    //set $server, $user, $password and $database_name, then establish the connection:
    $conn = new mysqli($server, $user, $password, $database_name);
    if ($conn->connect_error) {
        exit("FALSE");
    }
    //get employee detail from POST (sent via AJAX):
    $employee_detail = $_POST["employee_detail"];
    //here, you should test whether employee_detail matches what you expect
    //here, split $employee_detail into $first_name, $last_name and $company_name
    //now you are ready to send the MYSQL query:
    $sql = 'SELECT employeeid FROM tablename WHERE firstname = "$first_name" AND surname = "$last_name" AND companyname = "$company_name"';
    //since you expect a single matching result, you can test for num_rows == 1:
    if ((! $result = $_conn->query($sql)) || ($result->num_rows !== 1)) {
        exit("FALSE");
    } else {
        while ($row = $result->fetch_assoc()) {
            $employee_id = $row['id'];
        }
    }
    //now send $employee_id back to the AJAX call:
    echo $employee_id;

关于php - 如何使用 Ajax 根据另一个文本框的值填充表单输入文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564977/

相关文章:

php - 获取两个日期之间的日期列表并将数据插入数据库

php - 如何调整 jquery.simply-scroll 插件的 CSS 设置以占据全屏

php - 寻找分析大型对象上的 var_dump (PHP) 的简便方法

javascript - 使用 JS 和 CSS 的页面滚动 + 内部滚动 Div

javascript - 将按键或事件监听器添加到输入, "TypeError: ...addEventListener is not a function"

html - 在 div 的正方形中平铺 9 张图像......当前方式?

php - 忽略 PHP Web 服务中的 fatal error 和数据库异常

jquery - 在变量上使用 jQuery 而不是在 DOM 上?

javascript - 在 AngularJs 中选择 var 的值

javascript - IE 与 Firefox 链接(哈希与 htm5)