Search code examples
phpjqueryjsontypeaheadbloodhound

Typeahead Bloodhound, showing results as undefined. Wrong JSON type?


I am using Typeahead to make an autocomplete search textbox and the dropdown results are showing as undefined. Apparently the PHP does build the JSON, I have tested it. The problem might be a wrong JSON type. Here is the PHP:

$a_json = array();
$a_json_row = array();

while ($row = mysql_fetch_assoc($sql)) {

  //Replaces spaces for +
  $searchTerm = preg_replace('/\s/', '+', $row['products_keyword']);

  $a_json_row["search"] = $searchTerm;
  $a_json_row["label"] = $row['products_keyword'];
  array_push($a_json, $a_json_row);
}

echo json_encode ($a_json); //Return the JSON Array

And here is the script:

$(document).ready(function() {
  var keywordsVar = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('label'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: 'keywords.php?query=%QUERY'

  });

  keywordsVar.initialize();
  $('#idkeywords').typeahead({
    hint: false,
    highlight: true,
    minLenght: 2
  }, {
    name: 'keywords',
    displaykey: 'label',
    source: keywordsVar.ttAdapter()
  });
});

Here is an example of the JSON:

[{"search":"Artichokes","label":"Artichokes"},
{"search":"Artichokes+2","label":"Artichokes 2"},
{"search":"Artichokes+3","label":"Artichokes 3"}]

Can anyone spot the problem??


Solution

  • You have a typo in typeahead declaration. It should be displayKey with a capitalized k.

    Here is a Reference