twitter bootstrap typeahead ajax example
Starting from Bootstrap 2.1.0:
HTML:
<input type='text' class='ajax-typeahead' data-link='your-json-link' />
Javascript:
$('.ajax-typeahead').typeahead({
source: function(query, process) {
return $.ajax({
url: $(this)[0].$element[0].dataset.link,
type: 'get',
data: {query: query},
dataType: 'json',
success: function(json) {
return typeof json.options == 'undefined' ? false : process(json.options);
}
});
}
});
Now you can make a unified code, placing "json-request" links in your HTML-code.
You can use the BS Typeahead fork which supports ajax calls. Then you will be able to write:
$('.typeahead').typeahead({
source: function (typeahead, query) {
return $.get('/typeahead', { query: query }, function (data) {
return typeahead.process(data);
});
}
});
Edit: typeahead is no longer bundled in Bootstrap 3. Check out:
- Where is the typeahead JavaScript module in Bootstrap 3 RC 1?
- typeahead.js
As of Bootstrap 2.1.0 up to 2.3.2, you can do this:
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('/typeahead', { query: query }, function (data) {
return process(data.options);
});
}
});
To consume JSON data like this:
{
"options": [
"Option 1",
"Option 2",
"Option 3",
"Option 4",
"Option 5"
]
}
Note that the JSON data must be of the right mime type (application/json) so jQuery recognizes it as JSON.