Search code examples
jqueryajaxtwitter-bootstrapbootstrap-typeahead

Bootstrap 3 Typeahead Ajax


I'm using https://github.com/bassjobsen/Bootstrap-3-Typeahead

My code:

<input type="text" class="typeahead" autocomplete="off">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('.typeahead').typeahead({
        autoSelect: true,
        minLength: 2,
        delay: 400,
        source: function (query, process) {
            $.ajax({
                url: '/search/searchCities',
                data: {q: query},
                dataType: 'json'
            })
                .done(function(response) {
                    console.log(response.data);
                    return process(response.data);
                });
        }
    });
});
</script>

My backend code returns an json object like

{status: "OK", data: ["Moscow", "New York", "Odessa"]}

by php code

<?= echo json_encode(["status" => "OK", "data" => ["Moscow", "New York", "Odessa"]]) ?>

After I type 2 or more letters in the input there's an error in the browser console like this

GET http://localhost/search/searchCities?q=mo 200 OK
TypeError: a is undefined
...rep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==...

jquery.min.js (row 2, col 3476)
["Moscow"]

I see the dropdown with "Moscow" option, I can choose it and everything would be fine if i had not got the error in console. Please, show me my mistake.

I tried to use jquery.js (not the min-version). The error was

TypeError: elems is undefined
length = elems.length,

jquery.js (row 459, col 4)

I guess that something wrong with data type but i can't find it by myself.


Solution

  • It turned out that there is a mistake in bootstrap3-typeahead.min.js If I use bootstrap3-typeahead.js - no errors in the browser console.