Step 1 :create a table with the below sql query.
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 2 :Create index.php file.
Path: application/view/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
</head>
<body>
</body>
<script>
$(document).ready(function(){
$("#portLoading").select2({
ajax: {
url: "<?php echo base_url();?>/api/get_data.php",
type: "get",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
</script>
</body>
</html>
Step 3:Create the controller file Api.php.
Path: application/controllers/Api.php
<?php
require APPPATH . '/libraries/TokenHandler.php';
require APPPATH . 'libraries/REST_Controller.php';
class Api extends REST_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->tokenHandler = new TokenHandler();
header('Content-Type: application/json');
}
public function port_get(){
$searchTerm=$_GET['searchTerm'];
$this->load->model('api_model');
$portdata= $this->api_model->GetPort($searchTerm);
$data = array();
foreach($portdata as $row){
$data[] = array("id"=>$row->Name, "text"=>$row->Name);
}
echo json_encode($data);
}
}
Step 4: Create the model file api_model.php.
application/model/api_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Api_model extends CI_Model {
/* constructor */
function __construct()
{
parent::__construct();
/*cache control*/
$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
$this->output->set_header('Pragma: no-cache');
}
public function GetPort($searchTerm){
$this->db->like('Name', $searchTerm);
$query = $this->db->select("PortID,Name")->get('PortMst');
$portlist = $query->result();
return $portlist;
}
}