In this topics we will discuss how can we make data retrive by using Ajax with Codeigniter framework. In this system we will use DataTables Jquery plugin for display data in tabular format. Here we will implement DataTables server side processing by using Ajax using Codeigniter.
Controller to View
public function EventList()
{
$this->load->view('event_list');
}
HTML Code
<table id="datatable" class="table ">
<thead>
<tr>
<th>Location</th>
<th>Location Date & Time</th>
<th>Created Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Jquery Code (Datatable Plugin Code)
<script>
$(document).ready(function() {
$('#datatable').DataTable({
"ajax": '<?=base_url()?>Event/getEventDatatable',
"order": [[2, "desc" ]],
});
});
</script>
View to Controller (Event/getEventDatatable)
public function getEventDatatable()
{
$getdata = $this->Demand_Model->getEvent();
$data = array();
foreach ($getdata as $value)
{
$row = array();
$row[] = $value->location;
$row[] = $value->date_time;
$row[] = $value->created_date;
$row[] = '<a href="'.base_url().'event-edit/'.$value->id.'" class="btn btn-sm btn-success">Edit</a>';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
// Another Example
public function getEventDatatable()
{
$getdata = $this->Demand_Model->getEvent();
$data = array();
foreach ($getdata as $value)
{
$edit = '<a href="'.base_url().'event-edit/'.$value->id.'" class="btn btn-sm btn-success">Edit</a>';
$row = array($value->location,$value->date_time, $value->created_date ,$edit);
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Controller to Model ($this->Demand_Model->getEvent())
function getEvent()
{
$query = $this->db->get('crm_event');
return $query->result();
}