Codeigniter - How to fetch datatable data from ajax? - javascript

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>

Related

Codeigniter 3 using datatable cant get data using ajax

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.

Change active to inactive using buttons realtime

I am using DataTables with ajax using PHP CodeIgniter Framework. I am having a problem with switching Active buttons to Inactive buttons, vice versa.
What I want is:
When I click Active button, It should change to Inactive in realtime without refreshing the page.
Controller:
function activateStatus() {
$id = $this->uri->segment(3);
$data = array(
'status' => 1
);
$this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}
function deactivateStatus() {
$id = $this->uri->segment(3);
$data = array(
'status' => 0
);
$this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}
View:
<table class="table table table-hover table-bordered" id="equipmain">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
foreach ($equip as $row){
?>
<tr>
<td style="display: none;"><?= $row->id ?></td>
<td align="center">
<?php
$status = $row->status;
if($status == "1") { ?>
<button id="<?php echo $row->id ?>" class="btn btn-xs green-jungle statusupdate1">&#10003</button>
<?php } else { ?>
<button id="<?php echo $row->id ?>" class="btn btn-xs red-flamingo statusupdate0" >&#10005</button>
<?php } ?>
</td>
</tr>
</tbody>
</table>
AJAX:
var oTable = $('#equipmain').DataTable( {
"searching": false,
"processing":true,
"columnWidth": 20,
"serverSide": true,
"autoWidth": true,
});
$(document).on('click', '.statusupdate0', function() {
var id = $(this).attr("id");
$.ajax({
url: "<?= base_url() ?>Admin/activateStatus/" + id,
success: function (data) {
oTable.ajax.reload();
}
});
});
$(document).on('click', '.statusupdate1', function() {
var id = $(this).attr("id");
$.ajax({
url: "<?= base_url() ?>Admin/deactivateStatus/" + id,
success: function (data) {
oTable.ajax.reload();
}
});
});
I don't know where is the error why the buttons are not working.
It may be that you are missing the semicolon (;) after your base_url() call. In the AJAX section for both buttons, try changing <?= base_url() ?> to <?= base_url(); ?> and see if that solves the issue.

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() {
}
});
}

PHP / AJAX checkbox values

I'm trying to get all checked checkbox values and parse them to my php functin using AJAX.
I use foreach to try and get each id of the checked checkbox's.
My problem is that when I try and update the database, it doesn't return '1' which I echo upon success.
When I take my foreach code out, it works.
My delete button is :
<form class="form -dark" id="form-inline" method="POST">
<div class="btn-group">
<button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
</div>
</form>
My checkbox html/php code is :
<table class="table -dark -striped">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
<th style="text-align: center;">Token</th>
<th style="text-align: center;">Date/Time Generated</th>
<th style="text-align: center;">Status</th>
<th style="text-align: center;">Durbaility</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$username = $_SESSION['username'];
$token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
if(mysqli_num_rows($token_result) > 0) {
while($token_row = mysqli_fetch_array($token_result)) {
$result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";
echo '
<tr style="text-align: center;">
<td>
<center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
</td>
<td>
'.$token_row['token'].'
</td>
<td>
'.($token_row['time_generated']).'
</td>
<td>
'.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
</td>
<td>
'.$sub_struct.'
</td>
';
} }else{ ?>
<tr>
<td colspan="12" style="padding: 30px;">
<div class="alert -dark">
<div class="alert-icon _text-danger">
<i class="fa fa-exclamation-circle"></i>
</div>
No tokens in your account
</div>
</td>
</tr>
<?php } ?>
</tr>
</tbody>
Notice I need to use foreach to get each check checkbox value so I can remove the selected ones when I press the delete button.
My AJAX send to PHP function is :
<script>
function deleteSelectedTokens() {
var selectedTokens = document.getElementById("checkedTokens").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: selectedTokens
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
I think the problem is the Javascript... when I get the value of the checkboxes and post them, i think it's only getting 1 value inside the checkedTokens id.
My php receive code (this is not the problem) :
$username = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
My console.log has not errors. Like I said, i think it's the javascript code for getting the value of my checkbox's not getting all the values.
You can send json of checked items:
<script>
var selectedTokens = [];
$('#checkedTokens:checked').each(function(key, value){
selectedTokens.push($(value).val());
});
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
deleteSelectedTkns: true,
checked_id: JSON.stringify(selectedTokens)
},
success: function(msg){
if(msg == 1) {
update_myDays_success();
} else {
general_error_forms();
}
},
});
</script>
And your php code mysqli_real_escape_string give only string we should convert json to get array:
$selectedTokens = json_decode($_POST['checked_id']);
foreach($selectedTokens as $id) {
$doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
$result = $con->query($doUpdateDelete) or die("Error");
if($result)
{
echo '1';
}
else
{
echo 'Failed';
}
}
In html it is not allowed to assign the same id to multiple tags. (As already mentioned in the comments.)
If you place your checkboxes on a <form id="some_id">, and give every checkbox a unique name and id, you can use the function $('#some_id').serialize() to get the data of the form and post it to the server.

how to add<a> tag with laravel routing to a table rowusing jquery

How do I add a tag to a table row with Laravel routing using jQuery?
exam.blade.php
<td>
Time Table
Edit
<a href="{{ URL::Route('deleteExam', $exam->id) }}"
onclick="if (!confirm('Are you sure to delete this item?')){ return false; }"
title="Delete this Item"> <i class="glyphicon glyphicon-trash"></i> </a>
</td>
Can I write this above code using jQuery?
exam.blade.php
<td>
Time Table
Edit
<a href="javascript:void(0);" id="deleteItem" data-url="{{url('/')}}" title="Delete this Item" data-token="{{ csrf_token() }}">
<i class="glyphicon glyphicon-trash"></i>
</a>
</td>
Delete using jquery
$('#deleteItem').on('click',function(){
var token = $(this).data('token');
var base_url = $(this).data('url');
if(confirm('Are you sure to delete this item?')){
$.ajax({
url:baseurl+'/delete/'+$exam->id,
type: 'DELETE',
data: { _token :token},
success:function(msg){
alert("success");
}
});
}
else
return false;
});
I've created a helper class (gist here) specifically for dealing with tables and creating such action links. The helper will create all the table rows (including table header) with the $allowed model fields. When looping through the table rows, the createLinks() function in the helper class simply passes a $model_name for resource and the actual $obj.
So if your model is a form, and you passed the view an array of $forms from your controller, you can use the following:
The Route
Route::resource('form', 'FormController');
The View (ie: form/index.blade.php)
<?php
/**
* #var $forms {array} Form
*/
// Fields to show in table as name => label for table header
$allowed = array(
'id' => 'ID',
'name' => 'Name',
'description' => 'Description',
'created_at' => 'Created',
'updated_at' => 'Updated'
);
// Optional extras like a model name for action links
$extras = array(
'model' => 'form'
); ?>
<table class="make-datatable table table-responsive table-striped table-bordered" id="forms-table">
{!! TableHelper::createTable($forms, $allowed, $extras) !!}
</table>
The Helper Class
<?php
/**
* Class TableHelper
* #author Tom W. DeBerardine
*/
class TableHelper
{
public static function createHeaderRow($obj, $allowed, $extras = array())
{
$attributes = $obj[0]['attributes'];
$html = '<thead><tr>';
foreach ($allowed as $attribute => $nice_name) {
if (array_key_exists($attribute, $attributes)) {
$html .= '<th>' . $nice_name . '</th>';
}
}
if (array_key_exists('model', $extras)) {
$html .= '<th>Actions</th>';
}
$html .= '</tr></thead>';
return $html;
}
public static function createTableBody($obj, $allowed, $extras = array())
{
$html = '<tbody>';
foreach ($obj as $key => $value) {
$html .= '<tr>';
foreach ($allowed as $fkey => $field) {
$html .= '<td>' . $value->$fkey . '</td>';
}
if (array_key_exists('model', $extras)) {
$html .= TableHelper::createLinks($extras['model'], $value);
}
$html .= '</tr>';
}
$html .= '</tbody>';
return $html;
}
public static function createLinks($model_name, $obj)
{
$html = '<td>';
$html .= '' . 'Edit' . ' ';
$html .= '' . 'Show' . '';
$html .= \Form::open(array('url' => route($model_name . '.' . 'destroy', [$obj]), 'method' => 'delete'));
$html .= '<button type="submit" class="btn btn-danger btn-mini" onclick="
if (!confirm(\'Delete this object?\')) { return false; }"><i class="glyphicon glyphicon-trash"></i> Delete</button>';
$html .= \Form::close();
$html .= '</td>';
return $html;
}
public static function createTable($obj, $allowed, $extras = array())
{
return TableHelper::createHeaderRow($obj, $allowed, $extras) . TableHelper::createTableBody($obj, $allowed, $extras);
}
}
The Output
<table class="make-datatable table table-responsive table-striped table-bordered" id="forms-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Created</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Campaign 1</td>
<td>First campaign form</td>
<td>2016-01-01 15:59:39</td>
<td>2016-01-01 16:53:34</td>
<td>
Edit
Show
<form method="POST" action="http://demo.com/form/1" accept-charset="UTF-8">
<input name="_method" type="hidden" value="DELETE">
<input name="_token" type="hidden" value="aURptz3LWIZMXwefq1HYnvi4kteGsIObloBPWlgR">
<button type="submit" class="btn btn-danger btn-mini" onclick="
if (!confirm('Delete this object?')) { return false; }"><i class="glyphicon glyphicon-trash"></i> Delete
</button>
</form>
</td>
</tr>
</tbody>
</table>
This assumes you have working controller actions for the show, edit and delete functionality. If you want the delete button to submit the form via ajax, simply intercept the submit() event and put a check in your delete controller action for if the request is ajax (if( $request->ajax() ){ ...) to send a json response.

Categories