AJAX搜索表单:如何触发PHP查询?

时间:2018-05-12 14:21:24

标签: php jquery ajax forms search

我是AJAX的新手,我偶然发现了一个小问题。我的数据库中的页面有自定义搜索字段:

PHP:

 if(isset($_GET['fdf_search'])){
     $term_search = $_GET['fdf_search'];
     $fdf_pages = $mysqli_con->select("SELECT * FROM `pages` WHERE `alias` LIKE '%".$term_search."%'");
}

AJAX:

$(document).ready(function() {
$("#fdf-search").keyup(function() {
    // Assign $_GET['fdf-search'] to variable "searchKey" in js
    var searchKey = $('#fdf-search').val();
    if (searchKey == "") {
        //nothing
    }else{
        console.log('ajax called');
        $.ajax({
            type: "GET",
            url: "/fluidify/fdf-admin/functions/fdf_system_search.php",
            data: {
                search:searchKey
            },
            success: function(html){
                window.history.replaceState(null, null, "?fdf_search=" + searchKey + "");
            }
        });
    }
});
});

HTML:

<form action="" method="get">
    <input id="fdf-search" class="fdf-search" type="text" placeholder="zoeken" name="fdf_search" value="">
    <input class="fdf-search" type="submit" value="Zoeken" name="fdf_submit_search">
</form>

当我输入任何单词时,我希望我的AJAX触发PHP查询并查找并返回任何结果。现在window.history.replaceState(null, null, "?fdf_search=" + searchKey + "");正在更改我的网址中的GET,但出于某种原因,它什么也没做。

感谢所有帮助:)

编辑:select();类

public function select($query,$report = NULL){
    $result_array = array();
    $result_empty = false;
    $result = $this -> query($query);
    if($result !== false){
        while($row = $result -> fetch_assoc()){
            $result_array[] = $row;
        }
        return($result -> num_rows === 0) ? false : $result_array;
    }else{
        if($report === true){
            echo "error in query:";
            print_r($result);
            print_r($result_array);
            print_r($query);
            echo "<br>";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

要获得结果,您应该从您的PHP代码中输出一些内容,如下所示:

false

你的ajax调用应该是这样的:

 if(isset($_GET['fdf_search'])) {
     $term_search = $_GET['fdf_search'];
     $fdf_pages = $mysqli_con->select("SELECT * FROM `pages` WHERE `alias` LIKE '%".$term_search."%'");
     //output the result
     echo json_encode($fdf_pages);
 }