I'm using Bootstrap 3 with the compatible Typeahead (https://github.com/bassjobsen/Bootstrap-3-Typeahead).
The site runs on Django, and my query returns info from a local Postgres server.
When I try to use AJAX to retrieve the source, the dropdown doesn't appear.
console.log(data.suggestions)
prints an array of strings, so the AJAX call itself seems to be working. Am I doing something wrong with the process()
function?
My query returns a JSON file, in the format {"suggestions" : ["str1", "str2", "str3"] }
, so I use data.suggestions
to access the array containing my autocomplete candidates.
$('.typeahead').typeahead({
source: function (query, process) {
return $.getJSON(
'/path/to/query/',
{ query: query },
function (data) {
console.log(data.suggestions);
return process(data.suggestions);
});
}
});
However, when I pass in a static list as the source, the dropdown menu shows up and autocomplete works fine, so the problem seems to be specific to the AJAX call.
var list = ['apple', 'amazon', 'astronaut', 'amigo']
$('.typeahead').typeahead({
source:list
});
Here are the relevant parts of my html file with Django template files:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<div class="container">
<div class="starter-template">
<form class="form-inline">
<div class="form-group" id="results">
<input type="text" class="form-control input-lg typeahead" name="query" id="kanji" data-provide="typeahead" placeholder="Enter..." autofocus="true" autocomplete="off">
</div>
</form>
</div>
</div><!-- /.container -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="{% static 'js/bootstrap3-typeahead.min.js' %}"></script>
<script src="{% static 'js/script.js' %}"></script>
</body>
</html>
EDIT:
I tried some of the solutions to this question. However, the same thing still happens: the results print to the javascript console, but still doesn't generate a dropdown list of suggestions on the actual HTML page.
EDIT2: Bass Jobsen's example works perfectly on its own, which makes my own situation all the more puzzling.
In my example, I type phonetic words into the input box, and the query returns a list of possible kanji (chinese character) candidates. Typing "あ" should return a list like "亜", "相", "愛"...
I added minLength: 0
, and now when I leave the input field blank, the entire database comes up as a dropdown. But when I start typing, the dropdown disappears. So the query's working, the array is being recognized by Typeahead, but only when I have no input??