Search code examples
jqueryajaxtwitter-bootstraptypeahead.jsbootstrap-typeahead

Autocomplete suggestion not working for ajax


I have used bootstrap typeahead for autocomplete feature.

Following code is working perfect:

$(function () {
var $input = $(".typeahead");
$input.typeahead({
    source: [
       {id: "someId1", name: "Display name 1"},
       {id: "someId2", name: "Display name 2"}
    ],
    minLength: 2
});
});

But I want to use ajax search. So I have done changes as below:

$(function () {
var $input = $(".typeahead");
$input.typeahead({
    source: function(query, process) {
        return $.get('/search/good/auto-complete?term='+$('#search_searchtext').val());
    },
    minLength: 2
});
});

Above code executes ajax request but it does not show the suggestion from ajax response.

So please suggest me how can I do that.


Solution

  • Try

    $(function () {
        var $input = $(".typeahead");
        $input.typeahead({
            source: function(query, process) {
                return $.getJSON(
                    '/search/good/auto-complete?term='+$('#search_searchtext').val(),
                    //{ query: query }, // <- Maybe you can use it instead of ?term='+$('#search_searchtext').val()
                    function (data) {
                        var newData = [];
    
                        $.each(data, function(){
                            newData.push(this.name);
                        });
    
                        process(newData);
    
                        return;
                    });
            },
            minLength: 2
        });
    });