简体   繁体   中英

Twitter Typeahead results echoing to page but not returning to the search box PHP

I'm working with Twitter Typeahead to search for users in a database. I want it to show the closest result to their query while they're typing it. I'm using PHP on the backend.

I have the results I want echoing to the page if I add the query to the end of the url manually, and I can see in the Chrome Editor Network tab, that when I'm typing it's sending a request with the query I'm typing. Unfortunately the typeahead search box is never being populated with the results.

Here's the html for the search box:

<div class="row margin-top">
    <div class="small-12 large-2 columns">
        <input type="text" name="typeahead" class="search typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Search Here">
        <input type="submit" class="button">
    </div>
</div>
<!-- JAVASCRIPTS -->
<script src="/js/typeahead.min.js"></script>
<script src="/js/search.js"></script>

Here's my search.js:

$(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'typeahead',
        remote: {
            url : '/admin?query=%QUERY'
        },
        limit: 1
    });
});

And here's the search function in php:

function user_search($key)
{ 
    $link = open_database_connection();

    $array = array();

    $sql = "SELECT name FROM users WHERE name LIKE '%{$key}%'";

    $stmt = $link->prepare($sql);

    //Execute
    $stmt->execute();

    foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
        $array[] = $row;
    }
    return json_encode($array);
}

If I change that last line from return json_encode($array); to echo json_encode($array); it echos the correct results to the page if I add the query to the url manually. But nothing happens when I return them.

The return statement in a function, returns the value to the caller. Obviously, echo sends it to the page. So echo or whatever it is you want to do, where user_search is called.

echo user_search()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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