I'm trying to integrate Twitter Typeahead into my Laravel (4.2.11) project (with Bootstrap 2.3.2).
I have results being returned as JSON (checked with Fiddler), but a single "undefined" is always displayed instead.
If I enter a search query that doesn't return any results, the "No Results" is displayed correctly.
//Simple query in Laravel
Route::get('/sidebar/clients/{q}', function($q)
{
$companies = DB::table('ViewCompanies')->select(array('CompanyID', 'FullCompanyName'))
->where('FullCompanyName', 'like', '%'. $q .'%')->get();
return Response::json(array('companies' => $companies));
});
//Javascript in page
var clients = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('FullCompayName'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/sidebar/clients/%QUERY',
filter: function (parsedResponse) {
// parsedResponse is the array returned from your backend
console.log(parsedResponse);
return parsedResponse;
}
}
});
clients.initialize();
$('#clients .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 3,
},
{
name: 'clients',
valueKey: 'CompanyID',
displayKey: 'FullCompanyName',
source: clients.ttAdapter(),
templates: {
empty: [
'<div class="tt-empty-message">',
'No Results',
'</div>'
],
header: '<h3 class="tt-tag-heading tt-tag-heading2">Matched Companies</h3>'
}
});
My console log using the above code:
Thanks to Eduardo for giving me the idea of needing to parse my JSON into a JS array.
Doing a search revealed these two questions:
from which I was able to devise my one-line solution (full remove filter show):