Hi friends! In this post, today we will create an autocomplete search box from the database using Codeigniter and ajax. We are going to create in live search thing something similar to Google search. When you start typing in the textbox, the related suggestions will show from the database. To implement this auto-complete search feature we need a jquery plugin called 'Select2'.
Select2 is an excellent JQuery plug-in that converts the regular select box with search functionality. It's really inappropriate to make the end-user skim through hundreds of options to pick just one. It added up a search filter feature to the dropdown (select box), this is populating results with the help of ajax.
Just follow the below steps to create a live search from the database.
Step 1. Creating a Database
Step 2. Creating a Model File SearchCountryModel.php
<?php
class SearchCountryModel extends CI_Model
{
function __construct()
{
parent::__construct();
}
function getCountry($str)
{
$this->db->select('id, country_name as name');
$this->db->like('country_name', $str);
$query = $this->db->get('tbl_country');
return $query->result();
}
}
?>
Step 3. Creating a Controller File SearchCountry.php
- index() - Index is the default method that simply loads the view file.
- search() - The Search function will be triggered from the ajax call. It receives the incoming search term values ('q'), communicate with the model and get the results matching with the search term, encodes them to JSON, and passes it back to the browser.
<?php
class SearchCountry extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
function index()
{
$this->load->view('SearchCountryView');
}
function search()
{
$q = $this->input->get('q');
$this->load->model('SearchCountryModel');
echo json_encode($this->SearchCountryModel->getCountry($q));
}
}
?>
Step 4. Creating a Controller File SearchCountry.php
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Live Search from Database With Example</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3>CodeIgniter Autocomplete Demo From Database With Example</h3>
<select id="country" name="country" class="itemName form-control" style="width:400px" ></select>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
$('#country').select2({
placeholder: '-Select Country-',
minimumInputLength: 1,
ajax: {
url: "<?php echo base_url();?>index.php/SearchCountry/search",
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
</body>
</html>

0 Comments