Typeahead.js JSON response not rendering

1.2k views Asked by At

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:

Chrome Console Log

2

There are 2 answers

0
SteB On BEST ANSWER

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):

        filter: function (parsedResponse) {
            console.log(parsedResponse);
            var parsedResponse = $.map(parsedResponse, function(el) { return el; });
            return parsedResponse;
        }            
1
Eduardo Pacios On

what is the output of the parsedResponse you are logging? I think DB::table returns an object, not an array. Try to replace the response like this:

return Response::json(array('companies' => $companies->toArray()));

Then log the results and format them in the "filter" function in the Bloodhound object. Hope it helps!