Home » Php » jquery – How to get output from php to typeahead?

jquery – How to get output from php to typeahead?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am using twitter typeahead and php as backend for getting data from mysql.But i am not able to see any suggestions when i start typing on the text box. i think because the php output has to be JSON encoded..

how can i encode the output

output:

echo '<a href="results.html" class="searchres" onclick="navigate()" style="color:#696969;text-decoration:none;"><img src='.$iurl.' class="icons" /><div class="results" style="color:#696969;text-decoration:none;">'."$fname".'</div><span style="color:#696969;text-decoration:none;" class="author">'.$caption.'</span></a>'."\n";

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Twitter Typeahead</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script  type="text/javascript" src="../js/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'countries',
        prefetch: 'getvalues.php',
        limit: 10
    });
});  
</script>
<style type="text/css">
.bs-example{
    font-family: sans-serif;
    position: relative;
    margin: 100px;
}
.typeahead, .tt-query, .tt-hint {
    border: 2px solid #CCCCCC;
    border-radius: 8px;
    font-size: 24px;
    height: 30px;
    line-height: 30px;
    outline: medium none;
    padding: 8px 12px;
    width: 396px;
}
.typeahead {
    background-color: #FFFFFF;
}
.typeahead:focus {
    border: 2px solid #0097CF;
}
.tt-query {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}
.tt-hint {
    color: #999999;
}
.tt-dropdown-menu {
    background-color: #FFFFFF;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    margin-top: 12px;
    padding: 8px 0;
    width: 422px;
}
.tt-suggestion {
    font-size: 24px;
    line-height: 24px;
    padding: 3px 20px;
}
.tt-suggestion.tt-is-under-cursor {
    background-color: #0097CF;
    color: #FFFFFF;
}
.tt-suggestion p {
    margin: 0;
}
</style>
</head>
<body>
    <div class="bs-example">
        <input type="text" class="typeahead tt-query" autocomplete="off" spellcheck="false">
    </div>
</body>
</html>         

getvalues.php

  <?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;

$sql = "select file_name,img_url,captions from completer";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
    $fname = $rs['file_name'];
    $iurl = $rs ['img_url'];
    $caption = $rs ['captions'];
    echo '<a href="results.html" class="searchres" onclick="navigate()" style="color:#696969;text-decoration:none;"><img src='.$iurl.' class="icons" /><div class="results" style="color:#696969;text-decoration:none;">'."$fname".'</div><span style="color:#696969;text-decoration:none;" class="author">'.$caption.'</span></a>'."\n";
}
?>
How to&Answers:

First of all, to encode the output as JSON, you have to build an array with the results and use json_encode(), like so:

$return = array();
while($rs = mysql_fetch_array($rsd)) {
    $result[] = "...";
}
echo json_encode($result);

But by default results are html escaped before shown in typeahead, so you wan’t get the result you expect, but see the HTML codes in the suggestion list. To design entries with custom HTML you should use Templates as described here.

Your $result array entries could look like this to provide the fields you have in your html:

$result[] = array(
    "iurl" => "...",
    "fname" => "...",
    "caption" => "..."
);

… and then be filled in the template as described.

Another thing: The prefetch option, you are using isn’t one of typeahead, but of bloodhound, which is usually used together with typeahead, but needs to be initialized first and is given to typeahead as the source. Have a look here, it’s quite easy.

Bloodhound on it’s part can take fixed datasets as arrays (via the local option), fixed datasets via URL (via the prefetch option) or can do queries to URLs, which is what you apperently want to do, as you fetch the value of $_GET["q"] in your PHP code. In that case you’d have to use $q in your SQL and initialize bloodhound with the remote option like this:

remote: {
    url: 'getvalues.php?q=%QUERY',
    wildcard: '%QUERY'
}

You don’t need to do that, as it will be filtered again on the client side by typeahead.js … it’s just a question of performance and the amount of results. If there are just a few, use bloodhounds prefetch option.

Answer:

First of all you should use mysqli instead of mysql and also you are not useing your $_GET in your query. Not sure if it is needed.

For your code, not sure how to use the prefetch. I myself use bloodhound which is also been used on the official twitter typeahead github. It looks like this:

var countries= new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 100,
    remote: {
        'cache': false,
        url: 'ajax/getvalues.php?q=%QUERY',
        wildcard: '%QUERY',
        filter: function (data) {
            return data;
        }
    }
});

countries.initialize();

This will get the data from your server via ajax call. You return a JSON without all the html markup from your ajax call to your typeahead. The html markup can be done in typeahead

$('.typeahead').typeahead({
    highlight: true
}, {
    name: 'countries',
    source: producten.ttAdapter(),
    displayKey: 'artikelNaam',
    templates: {
        suggestion: function (countries) {
            result='<a href="results.html" class="searchres" onclick="navigate()" style="color:#696969;text-decoration:none;">'+
                '<img src='+countries.img_url+' class="icons" />'
                '<div class="results" style="color:#696969;text-decoration:none;">'+
                    countries.file_name+
                '</div>'+
                '<span style="color:#696969;text-decoration:none;" class="author">'+
                    countries.captions+
                '</span>'+
            '</a>';
            return result;
        }
    }
});

And your php file should look like this:

<?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;

$sql = "select file_name,img_url,captions from completer";
$rsd = mysql_query($sql); //should change to mysqli_query($con,$sql) where $con is your connection in config.php
while($rs = mysqli_fetch_assoc($rsd)) {
    $rows[]=$rs;
}
print json_encode($rows);
?>

Answer:

you may want to put your list for typeahead in a json file and change your script to this:

$(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'countries',
        prefetch: 'location/getvalues.json',
        limit: 10
    });
});      

The json file should be:

["country1","country2","country3"]