Search code examples
javascriptphphtmltypeahead

Fetching value from tag input to twitter typeahead js


I would like to take the value (or something like that) within tag input that I have in my HTML. Here's the input tag :

<input name="search" id="search" type="text" class="typeahead"/>

and I already did something like this to my script but it didn't work :

var labels = new Bloodhound({datumTokenizer: function(labels) {
return Bloodhound.tokenizers.whitespace(labels); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "http://localhost/codepen/search.php?term="+document.getElementsByTagName("input")[0].value,
filter: function(response) {
  return response.labels;
}}});

labels.initialize();

$('#search.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'labels',
displayKey: function(labels) {
return labels.label;
},
source: labels.ttAdapter()
});

In case search.php is needed :

<?php
$search = $_GET["term"];
require_once( "sparqllib.php" );
error_reporting(E_ERROR);
$db = sparql_connect( "http://localhost:3030/DOID/sparql" );
if( !$db ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
sparql_ns( "owl","http://www.w3.org/2002/07/owl#" );
sparql_ns( "rdfs","http://www.w3.org/2000/01/rdf-schema#" );
sparql_ns( "obo","http://purl.obolibrary.org/obo/" );

$sparql = 'SELECT DISTINCT ?class ?label ?description 
        WHERE { ?class a owl:Class . 
        OPTIONAL { ?class rdfs:label ?label} 
        OPTIONAL { ?class obo:IAO_0000115 ?description}
        FILTER regex (?label,"'.$search.'", "i")}';
$result = sparql_query( $sparql ); 
if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }

$fields = sparql_field_array( $result );

$resultarray = array();

while( $row = sparql_fetch_array( $result ) ){

    array_push($resultarray,array("label"=>$row['label']));
}
echo json_encode(array('labels'=>$resultarray));
?>

Any help would be appreciated.


Solution

  • Reading from the typehead documentation here : https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md

    You can see that the url has to be a static string.

    The prepare option which is a function is used to prepare the query.

    The wildcard parameter is used as a convenience option for prepare. If set, prepare will be a function that replaces the value of this option in url with the URI encoded query. See here

    So I guess your code should be :

    var labels = new Bloodhound({datumTokenizer: function(labels) {
    return Bloodhound.tokenizers.whitespace(labels); },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
    url: "http://localhost/codepen/search.php?term=%QUERY",
    wildcard: "%QUERY",
    filter: function(response) {
      return response.labels;
    }}});
    
    labels.initialize();
    ...
    

    Hope it solves your problem !