Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead shows results as undefined

I am trying to use typeahead to display google suggestions.

The Ajax call works fine and data is returned properly:

Before executing return process(data); data contains an array of strings that start with "w".

data = ["walmart", "weather", "wells fargo", "worldstarhiphop", "walgreens", "wikipedia", "white pages", "world cup", "webmd", "weather radar"]

However the suggestions displayed show "undefined" instead of real words. Any idea what I am missing here? Thanks.

enter image description here

    <input type="text" class="typeahead" placeholder="Search">


    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        source: function (query, process) {
            $.getJSON("Home/Suggest", { query: query }, function (data) {
                return process(data);
            });
        }
    });
like image 542
monstro Avatar asked Oct 18 '14 16:10

monstro


1 Answers

Update:

After some research, I found an answer to my question and will post it here, if someone needs it.

The trick is - the "process" callback function expects the results in a format:

[{value: "string1"}, {value: "string2"}, {value: "string3"}]

and not just an array of strings.

$('.typeahead').typeahead(
{ hint: true, highlight: true, minLength: 1 }, // options
{
    source: function (query, process) { // source dataset, data = array of strings
        $.getJSON('Home/Suggest', { query: query }, function (data) {
            //data=["string1", "string2", "string3"]
            //process callback function needs it 
            //in a format [{value: "string1"}, {value: "string2"}, {value: "string3"}]
            var output = $.map(data, function (string) { return { value: string }; });
            process(output);
        });
    }
});
like image 104
monstro Avatar answered Sep 20 '22 18:09

monstro