Hobby99 Hobby99 - 9 days ago 7
jQuery Question

Jquery Ajax Autocomplete with codeigniter 'term' issues

My ajax autocomplete does return the countries from the server but it does always show all countries whatever I type. There is something wrong with sending the request.term to controller to Model but I can't figure out what it is. Thanks very much for any hint!

html:

<input type='text' name='location_search' id='location_search' placeholder='Type Location' >


js:

$(function(){
var $sfield = $('#location_search').autocomplete({
source: function(request, response){
var url = "<?php echo site_url('autocomplete/control_areas'); ?>";
$.post(url, {data:request.term}, function(data){
response($.map(data, function(countries) {
return {
value: countries.name_en
};
}));
}, "json");
},
minLength: 2,
autofocus: true
});
});


controller:

function control_areas(){
$this->load->model('autocomplete_model');
$term = $this->input->get('term', TRUE);
$countries = $this->autocomplete_model->get_areas($term);
echo json_encode($countries);
}


model:

function get_areas($term){
$this->db->where('name_en', $term);
$query = $this->db->get('countries');
return $query->result();
}

Answer

The problem is in your model, it should be like this:

function get_areas($term){
    $this->db->like('name_en', $term, 'after');
    $query = $this->db->get('countries');
    return $query->result(); 
}