Reputation: 247
I am making an autocomplete search field in CodeIgniter, but it's not working properly. There is limit of 10 but every time when I enter the character the list became long and long like showing in the images:
here is my controller:
function search_fields(){
$country_id = $this->input->get('term');
$data['var']= $this->Travel->search_field($country_id);
echo json_encode($data['var']);
}
here is my model:
function search_field($country_id){
$this->db->distinct();
$this->db->select("destination");
$this->db->from('travels_detail');
$this->db->like('destination', $country_id);
$this->db->group_by('travels_detail.destination');
$this->db->limit(10);
$query = $this->db->get();
return $query->result();
}
and here is my view:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#text').keyup( function() {
var min_length = 0;
var keyword = $('#text').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'http://localhost/new/index.php/travels/search_fields',
type: 'POST',
dataType: 'json',
data: { term: $("#text").val()},
success:function(data){
$.each(data, function() {
$.each(this, function(k, v) {
$("#demo").append("<li>" + v + "</li>");
});
});
}
});
} else {
$('#demo').hide();
}
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" name="text" id="text" autocomplete="off" >
</form>
<ul id="demo"> </ul>
</body>
</html>
Also I want that user can select the value of input field from drop down. Anyone have any idea?
Upvotes: 1
Views: 5194
Reputation: 2713
In Model return result_array
:
return $query->result_array();
In Controller :
$search_data = $this->Travel->search_field($term);
echo json_encode($search_data);
Now, you can use jquery autocomplete for retrieving values from database.
<script>
$(document).ready(function() {
$(function(){
$( "#text" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://localhost/new/index.php/travels/search_fields",
data: { term: $("#text").val()},
dataType: "json",
type: "POST",
success: function(data){
var resp = $.map(data,function(obj){
return obj.destination;
});
response(resp);
}
});
},
minLength: 2
});
});
});
</script>
Upvotes: 0
Reputation: 1774
You forgot clean the html from #demo.When the success property occurs in Ajax Remove All Contents from #demo :
success:function(data){
$("#demo").html('');
$.each(data, function() {
$.each(this, function(k, v) {
$("#demo").append("<li>" + v + "</li>");
});
});
}
Upvotes: 2