Harris Khan Harris Khan - 22 days ago 9
Ajax Question

How to show array in html form is an autocomplete search field in codeigniter

I made an autocomplete search field using codeigniter, the result is coming in an array like

({"destination":"Accra"},{"destination":"Lagos"})


and I want to convert it into the html and show in drop down of input field. I tried many different method but could succeed, Kindly help me out.

Here is the code of my view, model and controller:

View:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>


</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<script>
$(document).ready(function(){
$('#country_id').keyup( function() {
var min_length = 0;
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'http://localhost/new/index.php/travels/search_fields',
type: 'POST',
data: { term: $("#country_id").val()},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
});
});
</script>

<form action="" method="post">
<input type="text" name="country_id" id="country_id" onKeyUp="do_search();" >

<ul id="country_list_id"> </ul>
</form>

</body>
</html>


Model:

public function search_field($country_id){
$this->db->select("destination");
$this->db->from('travels_detail');
$this->db->like('destination', $country_id);
$query = $this->db->get();
return json_encode($query->result_array());
}


Controller:

public function search_fields(){
$this->load->helper('form');
$country_id = $this->input->post('term');
$data['var']= $this->travel->search_field($country_id);
echo $data['var'];
}

Answer

If your data is coming ok from the server(as a json), try this to create your list:

success: function(data) {
    var $countryList = $('#country_list_id');

    // Clear the list
    $countryList.empty();

    // Append all items as <li> elements
    data.forEach(x => {
        $countryList.append("<li>" + x.destination + "</li>");
    });

    // Show the list
    $countryList.show();
}