根据位置标签填充下拉菜单

时间:2019-01-16 09:37:59

标签: javascript php html ajax

我有一个名为location_tags的数据库,我想尝试做的是允许用户键入他们的位置,下拉列表应仅填充具有匹配位置标签的用户而不显示其中没有位置标签的广告。这是我的桌子。 enter image description here

<?php

$conn = new mysqli('localhost', 'root', '', 'tutors') 
or die ('Cannot connect to db');

    $result = $conn->query("select id,name,Location_tags from tutor_location");
?>
<html>
<body>
<input type="text" name="location_input" id="location_input">
<select name="locations" id="locations">
    <script> 
        $("#location_input").keydown(function(){
            const location = $("#location_input").val();
            $("#locations").hmlt(''); //reset dropdown
            // do ajax call to get locations
            $.ajax({
                url: 'search.php',  //replace this with your route of the search function
                data: {location}, //pass location as body data
                dataType: 'json' //expect a json response back
                success: function(data) {
                    data.forEach(function(el) { //loop over the json response
                        let option = `<option id=${el.id} value=${el.name}>${el.name}</option>`
                        $("#locations").append(option); //append locations to select dropdown
                    });
                },
                error: function(err) {  //error functions
                    console.log(err);
                    alert("Error")
                }
            });
        });
    </script>
 <select name='id'>
<?php
    while ($row = $result->fetch_assoc()) {

                  unset($id, $name);
                  $id = $row['id'];
                  $name = $row['name']; 
                  echo '<option value="'.$id.'">'.$name.'</option>';

}
?>
</select>
</body>
</html>

和我的search.php代码:

   <?php
function SearchLocations() {
    $conn = new mysqli('localhost', 'root', '', 'tutors') or die ('Cannot connect to db');
    $result = $conn->query("select * from tutor_location where Location_tags LIKE ='%". $_GET['location']."%'");

    $locations = [];

    while ($row = $result->fetch_assoc()) {
        $locations[] = $row;    

    }

    return json_encode($locations);

}

?>

因此,例如,如果某人键入Mayfair,则下拉列表中仅应显示数据库中的第一个人,我面临的问题是所有项目都在显示而不是基于位置并且没有显示在下拉列表中

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

您可以在单独的PHP文件中构建搜索功能,以获取干净的URL路由。请注意,此查询将易于进行SQL注入。这只是一个一般示例

例如

//  search.php
//  GET request
    function SearchLocations() {
        $conn = new mysqli('localhost', 'root', '', 'tutors') or die ('Cannot connect to db');
        $result = $conn->query("select id,name,Location_tags from tutor_location where Location_tags='%". $_GET['location']."%'");

        $locations = [];

        while ($row = $result->fetch_assoc()) {
            $locations[] = $row;            
        }

        return json_encode($locations);

    }

HTML:

<input type="text" name="location_input" id="location_input">
<select name="locations" id="locations">

然后在您的JavaScript代码中:

 $("#location_input").keydown(function(){
            const location = $("#location_input").val();
            $("#locations").hmlt(''); //reset dropdown
            // do ajax call to get locations
            $.ajax({
                url: 'search.php',  //replace this with your route of the search function
                data: {location}, //pass location as body data
                dataType: 'json' //expect a json response back
                success: function(data) {
                    data.forEach(function(el) { //loop over the json response
                        let option = `<option id=${el.id} value=${el.name}>${el.name}</option>`
                        $("#locations").append(option); //append locations to select dropdown
                    });
                },
                error: function(err) {  //error functions
                    console.log(err);
                    alert("Error")
                }
            });
        });