Live Search results from database using AJAX, JSON

时间:2018-02-03 10:24:53

标签: php mysql json ajax

my script returns an array of JSON, and not individual results from the database. The script is designed to retrieve from the database records that match the text you typed. Below my codes, what could be wrong?

PHP:

//after connect to database (succesfull)
if($_GET['search_data'])
{
    $search = ltrim($_GET['search']);
    $limit = 15;
    header("Content-type: application/json; charset={$charset}");

    $res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
    $data = array();
    while($row = $res->fetch_accoss())
    {
        $row['name'] = htmlspecialchars_uni($row['name']);
        $data[] = array('id' => $row['aid'], 'text' => $row['name']);
    }
    echo json_encode($data);
    exit;
}

HTML

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
        $(document).ready(function(){
        $("#search").keyup(function(){
            var text = $(this).val();
            $.ajax({
                type: "POST",
                url: "search.php?get=search_data",
                dataType: 'JSON',
                data: "text=" + text,
                async: false,
                success: function(text) {
                    if(text)
                    {
                            $('#display').append(JSON.stringify(text))
                    }
                    else
                    {
                        $('#display').append('No results!');
                    }
                }

            });
        });
    });</script>
        <title>Live search</title>
    </head>
    <body>
        <br />
        search: <input type="textbox" value="" name="search" placeholder="Write here..." id="search" />
        <br />
        <div id="display"></div>
</html>

and results:

[{"id":"10","text":"Dropdowns"},{"id":"9","text":"Accordions"},{"id":"5","text":"Convert Weights"},{"id":"3","text":"Animated Buttons"},{"id":"8","text":"Side Navigation"},{"id":"6","text":"Parallax"},{"id":"2","text":"HTML Includes"},{"id":"7","text":"Progress Bars
"},{"id":"4","text":"Top Navigation"},{"id":"1","text":"Range Sliders"},{"id":"11","text":"Google Maps"}]

My problem is that it shows when you type some letters the whole array of JSON, and not only the record, which we expect. What can I do?

1 个答案:

答案 0 :(得分:0)

You're trying go get the search parameter with $_GET['search'] you need to use $_POST['text']. Try this :

if($_GET['search_data'])
    {
        $search = ltrim($_POST['text']);
        $limit = 15;
        header("Content-type: application/json; charset={$charset}");
    if(!empty($search)
        $res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
        $data = array();
        while($row = $res->fetch_accoss())
        {
            $row['name'] = htmlspecialchars_uni($row['name']);
            $data[] = array('id' => $row['aid'], 'text' => $row['name']);
        }
        echo json_encode($data);
        exit;
    }

And it's a good practice to use object in your ajax data

$(document).ready(function () {
        $("#search").keyup(function () {
            var text = $(this).val();
            $.ajax({
                type: "POST",
                url: "search.php?get=search_data",
                dataType: 'JSON',
                data: {
                    text: text
                },
                async: false,
                success: function (text) {
                    if (text)
                    {
                        $('#display').append(JSON.stringify(text))
                    } else
                    {
                        $('#display').append('No results!');
                    }
                }

            });
        });
    });