Codeigniter 3 using datatable cant get data using ajax - javascript

I found an error with my coding.
I here want to display data in DataTables with ajax. For the filter itself, it is dynamic so that the filter can be more than 1 depending on what is made. But when I want to display the data, there is an error which I don't know which side is the error. Here's the script:
By the way, im using CodeIgniter 3
View
<section class="content-header">
<div class="row" style="margin-left:15px; margin-right:15px; margin-bottom: 15px; ">
<div style="background-color: #E9fbf0; background-repeat:no-repeat; background-size:contain; background-position:center; padding: 30 0 0 10; border-radius: 15px; border:1px solid black;">
<div class="col-md-12">
<div class="table-responsive">
<table class="table" style="width: 100%;">
<tr>
<th class="action-th">Departemen</th>
<td><? echo $biodataSiswa['departemen']; ?></td>
</tr>
<tr>
<th class="action-th">Tahun Ajaran</th>
<td><? echo $biodataSiswa['tahunajaran']; ?></td>
</tr>
<tr>
<th class="action-th">Kelas</th>
<td><? echo $biodataSiswa['kelas']; ?></td>
</tr>
<tr>
<th class="action-th">NIS</th>
<td><? echo $biodataSiswa['nis']; ?></td>
</tr>
</table>
</div>
</div>
<input type="hidden" id="idmodul" name="idmodul" value="<? echo $idtabel; ?>"/>
<form id="filter-form">
<div class="row">
<? $no = 0;
foreach ($filter as $row) { ?>
<div class="col-md-3 col-sm-6 mb-3">
<label for=""><? echo $row?></label>
<select class="form-control" id="f_<? echo $no; ?>" name="f_<? echo $no; ?>">
<option value=''>Pilih</option>
<? foreach ($f_[$no] as $row) : ?>
<option value='<? echo $row['f1']; ?>'><? echo $row['f2']; ?> </option>
<? endforeach; ?>
</select>
</div>
<? $no++;} ?>
<br>
</div>
<div style="margin-top:20px;">
<input type="submit" name="submit" value="Filter" class="btn btn-primary d-inline">
</div>
</form>
<div class="row">
<div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example" style="width:100%;">
<thead>
<tr>
<th>Pelajaran</th>
<th>Nilai Angka</th>
<th>Nilai Huruf</th>
<th>Keterangan</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<!-- <div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example">
<thead>
<tr>
<th>Pelajaran</th>
<th>Nilai Angka</th>
<th>Nilai Huruf</th>
<th>Keterangan</th>
</tr>
</thead>
</table>
</div>
</div> -->
</div>
</div>
</section>
<div class="control-sidebar-bg"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var dataTable;
// var id = $('#idmodul').val();
dataTable = $('#example').DataTable({
"ajax": {
url : "<? echo base_url('viewtabel/ambil'); ?>",
type: "POST",
data: {
filter_data : function(){
return $('#filter-form').serialize();
},
idmodul : function(){
return $('#idmodul').val();
}
}
},
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
"aoColumns": [
{data : "f1"},
{data : "f2"},
{data : "f3"},
{data : "f4"}
],
"scrollCollapse": true,
"fixedColumns": {
"left": 1
},
'processing': true,
'language': {
"loadingRecords": ' ',
"processing" : '<i class="fa fa-spinner fa-spin" style="font-size:24px;color:rgb(75, 183, 245);"></i>'
},
"scrollX": true,
});
$('#filter-form').submit(function(e){
e.preventDefault();
dataTable.ajax.reload();
})
});
</script>
And, this is the Controller
<?
Header('Access-Control-Allow-Origin: *'); //for allow any domain, insecure
Header('Access-Control-Allow-Headers: *'); //for allow any headers, insecure
Header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); //method allowed
class Viewtabel extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper(array('path'));
$this->load->model('M_siswa');
$this->load->library('session');
$this->load->model('M_all');
$this->load->library('lib_connection');
$this->load->library('lib_menu');
$this->load->library('lib_menu_akademik');
$this->load->library('lib_changedate_toindo');
$this->load->library('lib_menu_departemen');
$this->db2 = $this->load->database('jibA', TRUE);
$this->db3 = $this->load->database('jibB', TRUE);
}
public function index() {
$accessToken = $this->session->userdata('token');
$link_api = $this->session->userdata('link_api');
$data['data_website'] = $this->M_all->getWesbiteData();
$arr_segment=$this->uri->segment_array();
if(isset($arr_segment[2])){
$action=strtolower(urldecode($arr_segment[2]));
} else
$action="";
switch($action){
default:
echo "Modul Tabel";
break;
case "load":
$data['data_website'] = $this->M_all->getWesbiteData();
$data['rows_menu3'] = $this->lib_menu_akademik->generate_menu();
$nis = $this->session->userdata('nis');
$emailtagihan = $this->session->userdata('email');
$bioSiswa = $this->M_siswa->getSiswaWithNis($nis,$emailtagihan);
$dataSiswa = $this->M_siswa->getDataByNis($nis);
$idKelas = $dataSiswa['idkelas'];
$id = $arr_segment[3];
$dataTabel = $this->M_all->getDataTabel($id);
$this->session->set_userdata('idmodul',$id = $arr_segment[3]);
$arrFilter = explode(',', $dataTabel['nama_filter']);
$arrQueryF = explode(' | ', $dataTabel['query_filter']);
$connection_id = $dataTabel['connection'];
$arrQueryF=str_replace('#NIS', "'".$nis."'",$arrQueryF);
$arrQueryF=str_replace('#DEPART', "'".$bioSiswa['departemen']."'",$arrQueryF);
// print_r($arrQueryF);
// print_R($arrQueryF);
for ($i = 0; $i < count($arrQueryF); $i++){
$arrQ[] = $this->M_siswa->getFilter($arrQueryF[$i]);
$data['f_'][$i] = $arrQ[$i];
}
$data['filter'] = $arrFilter;
// print_r($dataTabel['pk_tablebaru']);
$data['idtabel'] = $dataTabel['pk_tablebaru'];
$data['biodataSiswa'] = $bioSiswa;
$tglIndo = $this->lib_changedate_toindo->ubahIndo($bioSiswa['tgllahir']);
$data['tgllahirsiswa'] = $tglIndo;
$this->load->view("v_modultabel2.inc.php",$data);
break;
case "setting":
$ch5 = curl_init($link_api. 'extrarest/login-user');
curl_setopt($ch5, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $accessToken));
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true);
$oUser2 = json_decode(curl_exec($ch5));
$dept_uid = $oUser2->department;
$listmenu = $this->M_all->getMenuFromDepartemen($dept_uid);
$data['menuPerDept'] = $listmenu;
$data['menunya'] = $this->M_all->getMenu();
//$data['rows_menu'] = $this->lib_menu->generate_menu();
$data['rows_menu2'] = $this->lib_menu_departemen->generate_menu($dept_uid,$this->session->userdata('group'),$this->session->userdata('uid'));
$ch1 = curl_init($link_api. 'user/'. $this->session->userdata('uid'));
curl_setopt($ch1, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $accessToken));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
$oUser2 = json_decode(curl_exec($ch1));
if (!isset($oUser2)) {
print "Error accessing $link_api: \n" . curl_error($ch1);
}
elseif (isset($oUser2->error)) {
}
else {
}
curl_close($ch1);
$data['loguser'] = $oUser2;
$data['data_workspace'] = $this->M_all->getLinkApi1();
$data['data_website'] = $this->M_all->getWesbiteData();
//$mymenu=new Lib_menu();
//$ret=$mymenu-> generate_menu();
//$data=array('base_url'=>$base_url,'rows_menu'=>$ret);
//print_r($data['rows_menu']['level_1']);
$data_sidebar=$this->lib_menu->sidebar_menu();
$data['koneksi'] = $this->M_all->getAllConnection();
$this->load->view('v_modultabel2', $data);
$this->load->view("sidebar.php",$data_sidebar);
break;
case "post":
$nama_tabel = $this->input->post('nama_tabel');
$nama_filter = $this->input->post('nama_filter');
$query_filter = $this->input->post('query_filter');
$kolom_tabel = $this->input->post('kolom_tabel');
$query_data = $this->input->post('queryData');
$connection_id = $this->input->post('connection_id');
if($_POST['insert_mode']==1){
$postParams = array(
'pk_tablebaru' => '',
'nama_tabel' => $nama_tabel,
'nama_filter' => $nama_filter,
'query_filter' => $query_filter,
'kolom_tabel' => $kolom_tabel,
'query_data' => $query_data,
'connection' => $connection_id,
);
$this->M_all->InsertToTableBaru('tb_tablebaru',$postParams);
$last_id = $this->M_all->getLastIDTBBaru();
$l_id = $last_id['max(pk_tablebaru)'];
$url = base_url()."viewtabel/load/$l_id";
$this->db->query("UPDATE tb_tablebaru SET url = '$url' WHERE pk_tablebaru = '$l_id'");
redirect ('/viewtabel/setting/');
}
break;
case "del":
break;
case "ambil":
$filter_data = $this->input->post('filter_data');
parse_str($filter_data, $params);
$nis = $this->session->userdata('nis');
$idmodul = $this->session->userdata('idmodul');
$dataTabel = $this->M_all->getDataTabel($idmodul);
$queryDataTabel = $dataTabel['query_data'];
$queryDataTabel=str_replace('#NIS', "'".$nis."'",$queryDataTabel);
$queryDataTabel=str_replace('#f1','"'.$params['f_1'].'"',$queryDataTabel);
$queryDataTabel=str_replace('#f2','"'.$params['f_0'].'"',$queryDataTabel);
$getDatanya = $this->M_siswa->getDatanya($queryDataTabel);
print_r($queryDataTabel);
$json_data['data'] = $getDatanya;
echo json_encode($json_data);
break;
}
}
}
?>
at the Controller, i want to get the data from database. The variables used to enter the data are $getDatanya
This is the query :
SELECT c.nama AS f1,b.nilaiangka as f2,b.nilaihuruf as f3,b.keterangan as f4 FROM tabelB b LEFT JOIN tabelC c ON c.replid = b.idpelajaran LEFT JOIN tabelA a ON b.nis = a.nis AND a.aktif = 1 WHERE b.nis = #NIS AND b.idkelas = #f1 AND b.idsemester = #f2
Hopefully I can find a solution here. Thank you very much.

Related

Change cell background depending on mysql field value

I have the following code and my MySQL table has a column (not showing) called ativo. I need the $result_rowset['Nome'][$i] = $row['nome']; to have background-color changed to red if ativo = 0 and blue if ativo = 1.
Can anyone help me on this? I've tried so many ways found here but I couldn't customize anyone to my case.
Thanks in advance.
<?php
$result_rowset = array();
$i = 0 ;
while( $row = mysqli_fetch_array($result)) {
$result_rowset['Nome'][$i] = $row['nome'];
$result_rowset['Campo 01'][$i] = $row['campo1'];
$result_rowset['Campo 02'][$i] = $row['campo2'];
$result_rowset['Campo 03'][$i] = $row['campo3'];
$result_rowset['Campo 04'][$i] = $row['campo4'];
$result_rowset['Campo 05'][$i] = $row['campo5'];
$i ++ ;
}
$result->data_seek(0);
?>
<section class="feature-area section-gap" style="padding-top: 10px;">
<div class="container">
<div class="row d-flex justify-content-center" style="max-width: 1240px;">
<div class="mytable table-responsive">
<table class="table table-striped table-bordered table-hover">
<tbody>
<?php foreach ( $result_rowset as $result_key => $result_value ) { ?>
<tr>
<td><?php echo $result_key ; ?></td>
<?php foreach ( $result_value as $val ) { ?>
<td><?php echo $val ; ?></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</section>
First u need still save the column ativo when you fetch array
<?php
$result_rowset = array();
$i = 0 ;
while( $row = mysqli_fetch_array($result)) {
$result_rowset['Nome'][$i] = $row['nome'];
$result_rowset['ativo'][$i] = $row['ativo'];
$i ++ ;
}
$result->data_seek(0);
?>
and when you foreach the array you can add condition to make background color changed depends on column ativo
<table class="table table-striped table-bordered table-hover">
<tbody>
<?php foreach ( $result_rowset as $r ) { ?>
<tr>
<?php if($r->ativo==0){ ?>
<td style="background-color:red">
<?php }elseif($r->ativo==1){ ?>
<td style="background-color:blue">
<?php }else{ ?>
<td>
<?php } ?>
<?php echo $r->nome; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>

changing warning message in datatable

I have datatable and i have advance search using two combo box my problem is if i search some data and the data doesnt exist it shows warning like this DataTables warning: table id=myTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1. Now i want to change the warning like no job exist. Help me pls. im just student sorry for my english
this my code in my search.php
<section>
<div class="container">
<div class="row">
<div class="col-md-12">
<form id="myForm" class="form-inline">
<div class="form-group">
<label>Experience</label>
<select id="experience" class="form-control" name="exp">
<option disabled selected>Select Experience</option>
<?php
$sql = "SELECT DISTINCT(experience) FROM job_post WHERE experience is not null";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['experience']."'>".$row['experience']."</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<label>Qualification</label>
<select id="qualification" class="form-control" name="qua">
<option disabled selected>Qualification</option>
<?php
$sql = "SELECT DISTINCT(qualification) FROM job_post WHERE qualification is not null";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['qualification']."'>".$row['qualification']."</option>";
}
}
?>
</select>
</div>
<button id="" class="btn btn-success">Search</button>
</form>
</div>
</div>
<div class="row" style="margin-top: 5%;">
<div class="table-responsive">
<table id="myTable" class="table" style="width: 1190px;">
<thead>
<th>Job Name</th>
<th>Job Description</th>
<th>Minimum Salary</th>
<th>Maximum Salary</th>
<th>Experience</th>
<th>Qualification</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</section>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function(){
var oTable = $('#myTable').DataTable({
"autoWidth" : false,
"ajax" : {
"url" : "refresh_job_search.php",
"dataSrc": "",
"data" : function(d){
d.experience = $("#experience").val();
d.qualification = $("#qualification").val();
}
}
});
$("#myForm").on("submit", function(e){
e.preventDefault();
oTable.ajax.reload(null, false);
});
});
</script>
and this is my refresh_job_search.php
<?php
session_start();
require_once("db.php");
$sql = "SELECT * FROM job_post";
if (!empty($_GET['experience'])) {
$sql = $sql." WHERE experience = '$_GET[experience]'";
}
if (!empty($_GET['qualification']) && !empty($_GET['experience'])) {
$sql = $sql." AND qualification = '$_GET[qualification]'";
}else if(!empty($_GET['qualification'])){
$sql = $sql." WHERE qualification = '$_GET[qualification]'";
}
$result=$conn->query($sql);
if ($result->num_rows>0) {
while($row=$result->fetch_assoc()){
$json[] = array(
0 => $row['jobtitle'],
1 => $row['description'],
2 => $row['minimumsalary'],
3 => $row['maximumsalary'],
4 => $row['experience'],
5 => $row['qualification'],
);
}
echo json_encode($json);
}

I want to pass data in codeigniter from view using ajax post, process that data in controller and send back the result array to view

I have searched the whole WWW but get nothing helpful. Any Solution will be appreciated. thanks in advance
MY HTML
<div class="row">
Either the form tag needed in my case or not
<form>
<div class="form-group">
<label for="date" class="col-12 col-md-2 control-label"><?php echo 'Date';?>
</label>
<div class="col-12 col-md-3">
<input type="text" class="datepicker form-control" name="date" id="date">
</div>
</div>
Here I am getting the data from my database
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
I am using datatable class for exporting and printing
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
<th><div><?php echo get_phrase('options');?></div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach($attendance as $row):?>
$attendance is recieved from the controller in $this->load->view('backend/index', $page_data);
<tr>
<td><?php echo $count++;?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['student_id'];?></td>
<td><?php echo $row['class_id'];?></td>
<td><?php echo $row['date'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
MY JavaScript
The script below alert() the class_id and date but do not pass anything to the controller function
<script type="text/javascript">
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {"class_id": class_id, "date": date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
}
});
}
</script>
My Controller
If I give static value to $date and $class_id as $date = '04-04-2018'; $class_id = 2; inside manage_attendance() below it works but using $this->input->post() do nothing:
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1)
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
$this->load->view('backend/index', $page_data);
}
Try to change
url: '<?php echo base_url();?>index.php?admin/manage_attendance'
to
url: '<?php echo base_url();?>index.php/admin/manage_attendance',
You have to append data like this using jquery:
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {class_id: class_id, date: date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
var resultData = JSON.parse(response);
if(resultData!=null){
attendance= resultData.length;
}
if(attendance>0){
for(i=0;i<attendance;i++){
$(".attendance_listing").append("<tr><td>"+resultData[i].status+"</td><td>"+resultData[i].student_id+"</td><td>"+resultData[i].class_id+"</td><td>"+resultData[i].date+"</td></tr>");
}
}
}
});
}
//controler
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1){
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
echo json_encode($page_data);
}
}
I can get the same result by coding as following but I do not prefer that method/logic I want something as I have posted above
HTML
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
</tr>
</thead>
<tbody id="putdatahere">
</tbody>
</table>
JavaScript
<script type="text/javascript">
function get_attendance() {
var e = document.getElementById("class_id");
var class_id = e[e.selectedIndex].value;
var date = $('#date').val();
$.ajax({
url: '<?php echo base_url();?>index.php?admin/manage_attendance/'+ date +'/' + class_id,
success: function(response)
{
jQuery('#putdatahere').html(response);
}
});
}
</script>
CodeIgniter Controller
function manage_attendance($date, $class_id){
$query = $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
if($query){
$html_return = "";
foreach ($query as $attendance) {
$html_return .="<tr><td>";
$html_return .= $attendance['status']; //further Proccessing here e.g if $attendance['status'] == 0 echo absent otherwise present
$html_return .="</td><td>";
$html_return .= $attendance['student_id']); //further Proccessing here e.g get student name from its student_id
$html_return .="</td><td>";
$html_return .= $attendance['class_id']; //further Proccessing here e.g get class name from its class_id
$html_return .= "</td><td>";
$html_return .= $attendance['date'];
$html_return .="</td></tr>";
}
echo $html_return;
} else {
echo 'No record';
}
}

Unable to load data on dashboard via ajax

I have a partial view named SIM Balance in mine dashboard. This view should show the number of sims issued to a user date wise.
I have set up the controller
public function actionSimbalance()
{
$sql = "SELECT user.`name` AS issued_to, COUNT(`sims`.`id`) AS sims_issued, sims.`operator_name` AS operator_name,
CASE
WHEN sims.`status` = 'Production Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`status` = 'Testing Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Zong' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Mobilink' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
ELSE CAST(`sims`.`created_at` AS DATE) END AS issued_date
FROM `sims`
INNER JOIN `sim_issueance_transaction` ON (`sims`.`id` =
`sim_issueance_transaction`.`sim_id`)
INNER JOIN `user` ON (`sims`.`issued_to` = `user`.`id`)
WHERE sims.`status` IN ('Testing Stored SIM','Production Stored SIM')
GROUP BY user.`name`, sims.`status`, issued_date, sims.`operator_name`";
$rows = Yii::$app->db->createCommand($sql)->queryAll();
$output = [];
$grandtotal = 0;
foreach ($rows as $row) {
$std = new \stdClass();
$std->count = $row['sims_issued'];
$std->issued_to = $row['issued_to'];
$std->operator = $row['operator_name'];
$std->issued_date = $row['issued_date'];
$grandtotal += $std->count;
$output[]= $std;
}
return $this->renderPartial('sim_progress', ['model' => $output, 'grandtotal' => $grandtotal]);
}
The partial view sim_progress is below
<?php foreach ($model as $row){?>
<tr>
<td><?=$row->issued_to?></td>
<td><?=$row->count?></td>
<td><?=$row->operator?></td>
<td><?= $row->issued_date ?></td>
</tr>
<?php } ?>
<tr>
<td><strong>Grand Total</strong></td>
<td>
<strong><?= $grandtotal ?></strong>
</td>
<td></td>
</tr>
Then there is an HTML sim-balance I have designed
<div class="box box-info">
<div id="af8a8d88334">
<div class="print-header print-only">
<center><img style="width: 100px" src="<?=
\yii\helpers\Url::to('#web/images/logo.png', true); ?>"/>
</center>
<br/>
<hr/>
</div>
<div class="box-header with-border">
<h3 class="box-title">SIM Balance</h3>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<tr>
<th>Issued To</th>
<th>Sims Issued</th>
<th>Operator Name</th>
<th>Issued At</th>
</tr>
</thead>
<tbody id="dashboard-sim-balance">
</tbody>
</table>
</div>
</div>
</div>
<div class="box-footer clearfix">
<a href="javascript:void(0)" onclick="$('#af8a8d88334').printThis();"
class="btn btn-sm btn-default btn-flat pull-right">Print</a>
</div>
Then in my main site index view, I am calling it like below
.
.
.
<?php if (!Yii::$app->user->isGuest && in_array(Yii::$app->user->identity->user_role,[1,6])) {
echo $this->render('dashboard/sim-balance');
} ?>
.
.
.
.
$url_sim_balance = Url::toRoute('/dashboard/simbalance');
.
.
.
.
In my JS I am creating an ajax function which should show the details.
$script = <<< JS
$(document).ready(function () {
.
.
.
.
loadSimBalance();
.
.
.
});
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
JS;
$this->registerJs($script);
But when I run my project I cannot see the details but an empty table like below
How can I set my ajax call to view the details.
Any help would be highly appreciated.
change
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
To
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}

Codeigniter - How to fetch datatable data from ajax?

I'm working an application based on CodeIgniter. Here the code:
Controller:
public function index(){
$data = array(
'record' => $this->Parameter_model->get_parameter('tbl_parameter')
);
$this->site->view('parameter', $data);
}
Model:
public function get_parameter($table){
$query = $this->db->query("select * from $table order by 'parameter_ID' ASC");
if($query->num_rows() > 0){
foreach($query->result_array() as $row){
$data[] = $row;
}
$query->free_result();
}
else{
$data = NULL;
}
return $data;
}
View:
<table id="parameter" class="listdata table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="text-nowrap">Parameter</th>
<th class="text-nowrap">Method</th>
<th class="text-nowrap">Type</th>
<th class="text-nowrap">Action</th>
</tr>
</thead>
<tbody>
<?php if(!empty($record)):?>
<?php foreach($record as $row):?>
<tr align="center">
<td class="text-nowrap"><strong><?php echo $row['parameter_name'];?></strong></td>
<td class="text-nowrap"><?php echo $row['parameter_method'];?></td>
<td class="text-nowrap">
<?php
if($row['parameter_type'] == "1"){
echo "General";
}
else{
echo "COA Only";
}
?>
</td>
<td class="text-nowrap">
<div>
Edit
Lihat
Hapus
</div>
</td>
</tr>
<?php endforeach;?>
<?php endif;?>
</tbody>
<tfoot>
<tr>
<th class="text-nowrap">Parameter</th>
<th class="text-nowrap">Method</th>
<th class="text-nowrap">Type</th>
<th class="text-nowrap">Action</th>
</tr>
</tfoot>
</table>
Javascript:
// parameter
// Setup - add a text input to each footer cell
$('#parameter tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" style="width:100%;" title="Search '+title+'" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#parameter').DataTable({
paging: true,
searching: true,
ordering: true,
"order": [[ 0, "asc" ]],
scrollX: true,
scroller: true,
});
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
Above code work well.
Now, I want to fetch data into the table id="parameter" via ajax request. I've create an ajax request from url, lets say from here http://'+host+path+'/action/ambil, where var path = window.location.pathname; and var host = window.location.hostname;.
The ajax response produce:
{"record":[{"parameter_ID":"1","parameter_name":"pH","parameter_method":"(pH meter)","parameter_type":"1",{"parameter_ID":"2","parameter_name":"Viscosity","parameter_method":"(Brookfield-Viscometer)","parameter_type":"1"}]}
Question
How to configure datatable with Ajax data source, and how to display the data into the table, so I can use the data for example to create a link like code
<a href="<?=set_url('parameter/parameter_view/'.$row['parameter_ID']);?>">
You can do dataTable by server side script as follow.
Change your controller so that It will handle the server side call from datatable and you can create dynamic links in controller only. I have added comment in controller for more details.
Change your script to call it with ajax.
Don't load any thing in view tbody while loading page.
Note : I have skipped the model part I used direct query. Hope you can change it.
Contorller
public function index() {
$data = array();
if ($this->input->is_ajax_request()) {
/** this will handle datatable js ajax call * */
/** get all datatable parameters * */
$search = $this->input->get('search');/** search value for datatable * */
$offset = $this->input->get('start');/** offset value * */
$limit = $this->input->get('length');/** limits for datatable (show entries) * */
$order = $this->input->get('order');/** order by (column sorted ) * */
$column = array('parameter', 'method', 'type');/** set your data base column name here for sorting* */
$orderColumn = isset($order[0]['column']) ? $column[$order[0]['column']] : 'parameter';
$orderDirection = isset($order[0]['dir']) ? $order[0]['dir'] : 'asc';
$ordrBy = $orderColumn . " " . $orderDirection;
if (isset($search['value']) && !empty($search['value'])) {
/** creat sql or call Model * */
/** $this->load->model('Parameter_model');
$this->Parameter_model->get_parameter('tbl_parameter'); * */
/** I am calling sql directly in controller for your answer
* Please change your sql according to your table name
* */
$sql = "SELECT * FROM TABLE_NAME WHERE column_name '%like%'" . $search['value'] . " order by " . $ordrBy . " limit $offset,$limit";
$sql = "SELECT count(*) FROM TABLE_NAME WHERE column_name '%like%'" . $search['value'] . " order by " . $ordrBy;
$result = $this->db->query($sql);
$result2 = $this->db->query($sql2);
$count = $result2->num_rows();
} else {
/**
* If no seach value avaible in datatable
*/
$sql = "SELECT * FROM TABLE_NAME order by " . $ordrBy . " limit $offset,$limit";
$sql2 = "SELECT * FROM TABLE_NAME order by " . $ordrBy;
$result = $this->db->query($sql);
$result2 = $this->db->query($sql2);
$count = $result2->num_rows();
}
/** create data to display in dataTable as you want **/
$data = array();
if (!empty($result->result())) {
foreach ($result->result() as $k => $v) {
$data[] = array(
/** you can add what ever anchor link or dynamic data here **/
'parameter' => "<strong>".$v['parameter_name']."</strong>",
'method' => "<strong>".$v['parameter_name']."</strong>",
'parameter_type' => "<strong>".$v['parameter_name']."</strong>",
'actions' => "<strong>".$v['parameter_name']."</strong>"
);
}
}
/**
* draw,recordTotal,recordsFiltered is required for pagination and info.
*/
$results = array(
"draw" => $this->input->get('draw'),
"recordsTotal" => count($data),
"recordsFiltered" => $count,
"data" => $data
);
echo json_encode($results);
} else {
/** this will load by default with no data for datatable
* we will load data in table through datatable ajax call
*/
$this->site->view('parameter', $data);
}
}
View
<table id="parameter" class="listdata table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="text-nowrap">Parameter</th>
<th class="text-nowrap">Method</th>
<th class="text-nowrap">Type</th>
<th class="text-nowrap">Action</th>
</tr>
</thead>
<tbody>
/** tbody will be empty by default. **/
</tbody>
<tfoot>
<tr>
<th class="text-nowrap">Parameter</th>
<th class="text-nowrap">Method</th>
<th class="text-nowrap">Type</th>
<th class="text-nowrap">Action</th>
</tr>
</tfoot>
</table>
Script
<script>
$(document).ready(function() {
$('#example').DataTable({
url: '<?php base_url(); ?>controllerName/index',
processing: true,
serverSide: true,
paging: true,
searching: true,
ordering: true,
order: [[0, "asc"]],
scrollX: true,
scroller: true,
columns: [{data: "parameter"}, {data: "method"}, {data: "parameter_type"}, {data: "action"}]
/** this will create datatable with above column data **/
});
});
</script>
If you wish to use some third party library check this.
For your model query you can customize it as mention in this post.
You can check this article. Although I have written it using raw php, you can implement it quite easily by creating a separate library using that ssp class & can create this type of links.
Updated with More explanation and more code
You can try my code this is working fine for me.
Controller Code
public function showFeeCode()
{
$data = $this->fmodel->fetchAllData('*','fee_assign',array());
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $value) {
$button = "";
$button .= "<button class='btn btn-success fa fa-pencil' onclick='editFunction(".$value['id'].")' data-toggle='tooltip' title='Edit Details'></button> ";
$result['data'][$key] = array(
$value['feegroup'],
$value['name'],
$button
);
}
}
echo json_encode($result);
}
Modal Code
public function fetchAllData($data,$tablename,$where)
{
$query = $this -> db
->where($where)
-> get($tablename);
if($query->num_rows() > 0){
return $query->result_array();
}
else{
return array('error');
}
}
view code (table)
<table id="myTable" class="table display">
<thead class="alert alert-danger">
<tr>
<th>Fee Type</th>
<th>Fee Code</th>
<th>Action</th>
</tr>
</thead>
</table>
ajax code to fetch the data the ajax code recides in the view page.
$(document).ready(function() {
$('#myTable').dataTable( {
"ajax":"<?= base_url('Fee/showFeeCode'); ?>",
'order':[],
});
});
if you want to pass some parameter to the controller then you can pass it by ajax
$(document).ready(function() {
var id = 4;
$('#myTable').dataTable( {
"ajax":"<?= base_url('Fee/showFeeCode'); ?>/"+id,
'order':[],
});
});
You can receive this id with the help of passing parameter to the controller function.
if you want to send multiple data then you can use this format
var first_data = 1;
var second_data = 2;
$('#myTable').dataTable( {
"ajax": {
"url": '<?php echo base_url('fetchData') ?>',
"type": "POST",
"data": {first_data:first_data,second_data:second_data}
},
'order':[],
});
});
Model Code
public function get_cities(){
$this->db->order_by('city_id','desc');
$this->db->limit('1000');
$this->db->select('*,cities.name as city_name');
$this->db->from('cities');
$this->db->join('states','states.id=cities.state_id','left');
$this->db->join('countries','countries.id=states.country_id','left');
$data=$this->db->get();
return $data->result_array();
}
private function get_datatables_query_city(){
$column_search = array('cities.name','states.name','countries.country_name');
$order = array('city_id' => 'desc');
$column_order = array(null, 'city_name', 'sname', 'country_name', null);
$this->db->select('cities.city_id,cities.name as city_name,states.name as sname,states.id as state_id,countries.id as country_id,countries.country_name');
$this->db->from('cities');
$this->db->join('states','states.id=cities.state_id','left');
$this->db->join('countries','countries.id=states.country_id','left');
$i = 0;
foreach ($column_search as $item)
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0)
{
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order']))
{
$this->db->order_by($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($order))
{
$order = $order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables_city()
{
$this->get_datatables_query_city();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered_city()
{
$this->get_datatables_query_city();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all_city()
{
$this->db->from('cities');
return $this->db->count_all_results();
}
Controller Code
public function city_list(){
$this->load->view('admin/header');
$this->load->view('admin/city');
$this->load->view('admin/footer');
}
public function city_ajax(){
$list = $this->Admin_model->get_datatables_city();
$data = array();
$no = $_POST['start'];
foreach ($list as $city){
$no++;
$row = array();
$row[] = $no;
$row[] = $city->city_name;
$row[] = $city->sname;
$row[] = $city->country_name;
$row[] = '<div class="d-flex align-items-center card-action-wrap">
<div class="inline-block dropdown">
<a class="dropdown-toggle no-caret" data-toggle="dropdown" href="#" aria-expanded="false" role="button"><i class="ion ion-ios-more"></i></a>
<div class="dropdown-menu dropdown-menu-right" x-placement="top-end" style="position: absolute; transform: translate3d(-214px, -161px, 0px); top: 0px; left: 0px; will-change: transform;">
<a class="dropdown-item" href="'.base_url().'Adminhome/city_edit/'.$city->city_id.'" ><i class="fas fa-edit read-icon"></i> Edit</a>
<a id="mybutton" href="javascript:void(0);" onclick="citydelete('.$city->city_id.')" class="dropdown-item text-danger remove" data-toggle="modal" data-target="#delete" data-id="'.$city->city_id.'"><i class="fas fa-trash-alt read-icon text-danger"></i> Delete</a>
</div>
</div>
</div>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Admin_model->count_all_city(),
"recordsFiltered" => $this->Admin_model->count_filtered_city(),
"data" => $data,
);
echo json_encode($output);
}
view code
<div class="section-body">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped" id="example">
<thead>
<tr>
<th>Sr.Number</th>
<th>City Name</th>
<th>State Name</th>
<th>Country</th>
<th>Manage</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
Are you sure want to delete.
</div>
<div class="modal-footer bg-whitesmoke br">
<a id="confirm-button"> <button type="button" class="btn btn-danger">Delete</button></a>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<div class="alert alert-primary show2" role="alert" id="snackbar2" style="visibility: hidden">
Successfully Deleted
</div>
<script>
function citydelete(id){
$('#delete').modal('show');
rowToDelete = $(this).closest('tr');
$('#confirm-button').click(function(){
$.ajax({
url: '<?php echo base_url();?>/Adminhome/city_delete',
type: 'GET',
data: {id: id},
success: function (data){
$("#"+id).remove();
var table = $('#example').DataTable();
table.ajax.reload( null, false );
$("#delete").modal('hide');
document.getElementById("snackbar2").style.visibility = "visible";
setTimeout(function() {
document.getElementById('snackbar2').style.visibility = 'hidden';
}, 3000);
}
});
})
}
</script>
<script type="text/javascript">
var table;
$(document).ready(function() {
table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"stateSave": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('Adminhome/city_ajax')?>",
"type": "POST"
},
"columnDefs": [
{
"targets": [ 0 ],
"orderable": false,
},
],
});
});
</script>

Categories