简体   繁体   English

使用php和mysql的ajax搜索功能

[英]ajax search function using php and mysql

I'm using an ajax call to query my mysql db to search for a list of users.我正在使用 ajax 调用来查询我的 mysql 数据库以搜索用户列表。

here is the html;这是html;

<input type="text" id="partnerName" name="partnerName" class="form-control" placeholder="Type to search partners....">
   <div id="partnerList" style="background-color:#beb6ac;"></div>

Here is my function.这是我的功能。

$(document).ready(function() {
            $('#busTradingName').keyup(function() {
                var query = $(this).val();
                if (query != '') {
                    $.ajax({
                        url: "search/empsearch.php",
                        method: "POST",
                        data: {
                            query: query
                        },
                        success: function(data) {
                            $('#empList').fadeIn();
                            $('#empList').html(data);
                        }
                    });
                }
            });

            $(document).on('click', 'li', function() {
                $('#busTradingName').val($(this).text());
                $('#empList').fadeOut();
            });
        });

here is the query:这是查询:

    if(isset($_POST["query"])){
    $output = '';
    $query = "SELECT busTradingName FROM organisation WHERE busTradingName LIKE '%".$_POST["query"]."%'";
    $result = mysqli_query($connection, $query);
    $output = '<ul class="list-unstyled">';
    if(mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_array($result))
        {
            $output .= '<li>'.$row["busTradingName"].'</li>';
        }
    }
    else
    {

        $output .= '<li>Not Found</li>';
    }
    $output .= '</ul>';
    echo $output;
}

This works perfectly.这完美地工作。 But if i want to use the same function, in the same form, my other input fields get updated as well(Even tho the id is different and the query is in a different php file altogether. eg.但是,如果我想以相同的形式使用相同的功能,我的其他输入字段也会更新(即使 id 不同并且查询完全在不同的 php 文件中。例如。

this HTML;这个 HTML;

<input type="text" name="busTradingName" id="busTradingName" placeholder="Last employer's trading name">
    <div id="empList"></div>

This function;这个功能;

$(document).ready(function() {
            $('#partnerName').keyup(function() {
                var query = $(this).val();
                if (query != '') {
                    $.ajax({
                        url: "search/search.php",
                        method: "POST",
                        data: {
                            query: query
                        },
                        success: function(data) {
                            $('#partnerList').fadeIn();
                            $('#partnerList').html(data);
                        }
                    });
                }
            });

            $(document).on('click', 'li', function() {
                $('#partnerName').val($(this).text());
                $('#partnerList').fadeOut();
            });
        });

with this query;有了这个查询;

if(isset($_POST["query"])){
    $output = '';
    $query = "SELECT * FROM cards WHERE surname LIKE '%".$_POST["query"]."%'";
    $result = mysqli_query($connection, $query);
    $output = '<ul class="list-unstyled">';
    if(mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_array($result))
        {
            $output .= '<li>'.$row["surname"].'</li>';
        }
    }
    else
    {

        $output .= '<li>Not Found</li>';
    }
    $output .= '</ul>';
    echo $output;
}

This updates both input fields with the same data.这会使用相同的数据更新两个输入字段。 Any ideas why my query is not being passed to one specific input, but getting populated across my form?任何想法为什么我的查询没有被传递到一个特定的输入,而是在我的表单中填充?

On a closer look, both event handlers have something in common:仔细观察,两个事件处理程序有一些共同点:

<script type="text/javascript">
    $(document).ready(function () {
        // ...ajax for #partnerName...

        $(document).on('click', 'li', function () {
            $('#partnerName').val($(this).text());
            $('#partnerList').fadeOut();
        });

        // ...ajax for #busTradingName...

        $(document).on('click', 'li', function () {
            $('#busTradingName').val($(this).text());
            $('#empList').fadeOut();
        });
    });
</script>

Eg both are attached to the same element ( document ).例如,两者都附加到同一个元素( document )。 Also, in both situations, each click event is triggered on an element of type li .此外,在这两种情况下,每个click事件都会在li类型的元素上触发。 So, the two separated code snippets could, theoretical, be joined together into:因此,理论上,这两个分离的代码片段可以合并为:

<script type="text/javascript">
    $(document).ready(function () {
        // ...

        $(document).on('click', 'li', function () {
            $('#partnerName').val($(this).text());
            $('#partnerList').fadeOut();
            $('#busTradingName').val($(this).text());
            $('#empList').fadeOut();
        });
    });
</script>

This "arrangement" emphasizes the problem better.这种“安排”更好地强调了这个问题。 Eg that all inputs are beeing updated at the same time.例如,所有输入都同时更新。

In order to avoid this behaviour you can attach each event handler to the corresponding "parent" element, not anymore to the document .为了避免这种行为,您可以将每个事件处理程序附加到相应的“父”元素,不再附加到document The final code would then look something like this:最终的代码看起来像这样:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title></title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                //********************************************
                // Ops regarding the partner name.
                //********************************************

                $('#partnerName').keyup(function () {
                    var query = $(this).val();

                    if (query != '') {
                        $.ajax({
                            url: "search/search.php",
                            method: "POST",
                            data: {
                                query: query
                            },
                            success: function (data) {
                                $('#partnerList').fadeIn();
                                $('#partnerList').html(data);
                            }
                        });
                    }
                });

                $('#partnerList').on('click', 'li', function () {
                    $('#partnerName').val($(this).text());
                    $('#partnerList').fadeOut();
                });

                //********************************************
                // Ops regarding the trading name.
                //********************************************

                $('#busTradingName').keyup(function () {
                    var query = $(this).val();

                    if (query != '') {
                        $.ajax({
                            url: "search/empsearch.php",
                            method: "POST",
                            data: {
                                query: query
                            },
                            success: function (data) {
                                $('#empList').fadeIn();
                                $('#empList').html(data);
                            }
                        });
                    }
                });

                $('#empList').on('click', 'li', function () {
                    $('#busTradingName').val($(this).text());
                    $('#empList').fadeOut();
                });
            });
        </script>
    </head>
    <body>

        <!--<form method="post">-->
        <label>Partner name:</label>
        <input type="text" id="partnerName" name="partnerName" placeholder="Search for partners...">
        <div id="partnerList"></div>

        <br/>

        <label>Trading name:</label>
        <input type="text" id="busTradingName" name="busTradingName" placeholder="Search for last employer's trading name...">
        <div id="empList"></div>
        <!--</form>-->

    </body>
</html>

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

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