I search all questions about typeahead plugin in this forum and have tried all the ways i can. But i have a problem yet. Im using codeigniter and want to autocomplete by typeahead plugin via ajax. This is my js code:
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
source: function (query, process) {
$.ajax({
url: baseUrl + 'panel/yazilarim/deneme',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function (data) {
console.log(data);
process(data);
}
});
}
});
public function deneme() {
$aranan = $this->input->post("query");
$sorgu = $this->db->select("ad")->from("kategori")->where("ad LIKE '%" . $aranan . "%' ")->get();
$sonuclar = $sorgu->result_array();
$dizi = [];
foreach ($sonuclar as $sonuc) {
$dizi[] = $sonuc["ad"];
}
echo json_encode($dizi);
}
console.log()
function works well, i can see the result array, but the dropdown menu never appears. I've load bundle and typeahead js files and the css file. Any suggestions?
This is how i implemented typeahead in my CodeIgniter project. Please refer the my working code. In the view page
<script src="<?php echo base_url('assets/js/typeahead.min.js'); ?>" > </script>
<script>
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote:'<?php echo base_url(); ?>panel/yazilarim/deneme?query=%QUERY',
limit : 5
});
});
</script>
<div class="form-group">
<input type="text" name="member" class="form-control typeahead" style="width:280px;" autocomplete="off" >
</div>
In the controller
public function deneme() {
$aranan = $this->input->get("query");
$sorgu = $this->db->select("ad")->from("kategori")->where("ad LIKE '%" . $aranan . "%' ")->get();
$sonuclar = $sorgu->result_array();
$dizi = [];
foreach ($sonuclar as $sonuc) {
$dizi[] = $sonuc["ad"];
}
echo json_encode($dizi);
}
I think your controller is right. If it doesn't work please comment the problem below.Remember i use get method.
You forgot to return result. Please try this:
success: function (data) {
console.log(data);
return process(data);
}
Also, set async:false
property.
At a very basic level, you use an asynchronous mode when you want the call to occur in the background and a synchronous mode when you want your code to wait until the call has completed.
Here is asyncronous
version.
source: function (query, process) {
var getData = getData();
getData.done(function(data){
return process(data);
// do stuff with `information` here, not elsewhere.
});
function getData(){
return $.ajax({
url: baseUrl + 'panel/yazilarim/deneme',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON'
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.