Unable to load data on dashboard via ajax - javascript

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

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.

ajax or jquery doesn't show data Laravel

I added a search field to show live my data, but nothing works when I fill that field.
I made a route called retour.action, and that's in my controller, so when I try a console.log('test') i can see test in my Console on my browser, but the rest of the code I made doesn't work, and I also get no error
here is my controller
public function action(Request $request)
{
if ($request->ajax()) {
$output = '';
$query = $request->get('query');
if ($query != '') {
$retours = Returnorder::all()
->where('firmaname', 'like', '%' . $query . '%')
->orWhere('ordernumber', 'like', '%' . $query . '%')
->orWhere('status', 'like', '%' . $query . '%')
->get();
} else {
$retours = Returnorder::latest('id')->paginate(15);
}
$total_row = $retours->count();
if ($total_row > 0) {
foreach ($retours as $retour) {
$output .= '
<tr>
<td>' . $retour->firmaname . '</td>
<td>' . $retour->ordernumber . '</td>
<td>' . $retour->status . '</td>
</tr>
';
}
} else {
$output = '<tr>
<td align="center" colspan="5">Geen data gevonden</td>
</tr>
';
}
$retours = array(
'table_data' => $output,
);
echo json_encode($retours);
}
}
And this is my script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('retour.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(retours)
{
$('tbody').html(retours.table_data);
}
})
}
$(document).on('keypress', '#search', function(){
let query = $(this).val();
fetch_customer_data(query);
});
});
And the HTML is this
#extends('layouts.app')
#section('content')
<div class="container">
<div class="mTop">
<div class="row justify-content-center">
<div class="col-md-10">
#if(session('message'))
<div class="alert alert-success" role="alert">
{{session('message')}}
</div>
#endif
<div class="card">
<div class="card-header">Retourmeldingen</div>
<div class="card-body">
<div class="form-group" >
<label for="search" hidden>Zoeken</label>
<input type="text" name="search" id="search" class="form-control"
placeholder="Typ hier uw zoekopdracht in"/>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Firmanaam</th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col">Ordernummer</th>
<th scope="col">Status</th>
<th scope="col">Verwerkingstijd</th>
<th scope="col">Inzenddatum</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Help me please
I think you first need to be sure that what you're typing is actually being sent back to the router. You can get the value of what you're typing by using this:
$(function() {
$('#search').on('keyup', (e) => {
console.log(e.target.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" type="text" name="search" />

live search opetion in codeigniter with ajax

I am new to codeIgniter. want to learn this. I am facing problem. data is not populated in search page.
in model
function fetch_data($query)
{
$this->db->select('*');
$this->db->from('casedata');
if($query!='')
{
$this->db->like('status',$query);
}
$this->db->order_by('SrNo','DESC');
return $this->db->get();
}
in controller the fetch function not getting data from database
function fetch()
{
$output='';
$query='';
$this->load->model('crud_model');
if ($this->input->post('query'));
{
$query= $this->input->post('query');
}
$data=$this->Crud_model->fetch_data($query);
$output .='<div class="table-responsive">
<table class="table table_bordered table-striped
<tr>
<th>SrNo.</th>
<th>Tile</th>
<th>File No.</th>
<th>Division</th>
<th>Section</th>
<th>LDH</th>
<th>NDH</th>
<th>PDH</th>
<th>STATUS</th>
</tr>';
if($data->num_rows()>0)
{
foreach($data->result() as $row)
{
$output.='<tr> <td>'.$row->SrNo.'</td>
$output.='<tr> <td>'.$row->title.'</td>
<td>'.$row->fileno.'</td>
<td>'.$row->division.'</td>
<td>'.$row->section.'</td>
<td>'.$row->ldh.'</td>
<td>'.$row->ndh.'</td>
<td>'.$row->pdh.'</td>
<td>'.$row->status.'</td></tr>';
}
}
else{
$output.='<tr> <td colspan="5">No Data Found</td></tr> ';
}
$output.='</table>';
echo $output;
}
in view
<html>
<body>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary" data-collapsed="0">
<div class="panel-heading">
<div class="panel-title" >
<i class="entypo-plus-circled"></i>
<?php echo get_phrase('Search Data');?>
</div>
</div>
<div class="panel-body">
<?php echo form_open(base_url() . 'index.php?
admin/student/create/' , array('class' => 'form-horizontal form-groups-
bordered validate', 'enctype' => 'multipart/form-data'));?>
<div class="form-group">
<input type="text" name="search_text" id="search_text"
placeholder="Search by Customer Detsils" class="form-control"/>
<div id="result">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
load_data();
function load_data(query)
{
$.ajax({
url:"<?php echo base_url();?>index.php?
admin/fetch",method:"POST",
data:{query:query},
success:function(data){
$('#result').html(data);
}
})
}
$('#search_text').keyup(function(){
var search=(this).val();
if (search!='')
{
load_data(search);
}
else
{ load_data();
}
} );
});
</script>
Data is not populated in table. How to get output from this?
You need to loop throught the $data variable. please change the 'if' and 'foreach' as below code.
if(is_array($data) && count($data)>0)
{
foreach($data as $row)
{
still if it not working try var_dump($data) and check whether results are coming or not.

How to redirecting page to another page using ajax jquery in codeigniter?

am using codeigniter, am working shopping cart. after selecting of items to cart using ajax jquery. Here, items menu and cart table will be side by side displayed.
Now, my task is to copying cart items to another table, by clicking button,which is done. now problem is on clicking button i need to copied and at a time i need to route to another page.. here i can copy cart items to another table but i can't redirect to another.for this i used jquery ajax.
now i need route to page which in views folder users/basket.php
Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="row">
<div class="col-lg-12 text-center">
<?php if(isset($_SESSION['loggedin'])){?>
<div class="alert alert-success"><?php echo $_SESSION['loggedin'];?></div>
<?php } ?>
Hello, <?php echo $_SESSION['username']?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<table class="table table-condensed table-hover">
<tr>
<th class="text-center">Item</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Add</th>
</tr>
<?php foreach($items as $item):?>
<tr class="success">
<td><?php echo $item['product_name'];?></td>
<td class="text-center"><input type="text" name="quantity" id="<?php echo $item['product_id'];?>" class="quantity" maxlength="2" size="2"></td>
<td><?php echo $item['product_price'];?></td>
<td><button type="button" name="add_cart" class="add_cart" data-productname="<?php echo $item['product_name'];?>" data-price="<?php echo $item['product_price'];?>" data-productid="<?php echo $item['product_id'];?>"><i class="fa fa-plus-circle"></i></button></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div class="col-lg-6 col-lg-offset-1">
<div id="cart_details" class="text-center">
</div>
</div>
</div>
Product_controller.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
public function add(){
$this->load->library('cart');
$data = array(
'id' => $_POST["product_id"],
'name' => $_POST["product_name"],
'qty' => $_POST["quantity"],
'price' => $_POST["product_price"],
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
public function load(){
echo $this->view();
}
public function remove(){
$this->load->library('cart');
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
public function clear(){
$this->load->library('cart');
$this->cart->destroy();
echo $this->view();
}
public function view(){
$this->load->library('cart');
$output = '';
$output.='
<h3>Shopping cart</h3><br/>
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-danger"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
<br/>
<table class="table table-bordered">
<tr>
<th class="text-center">Name</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th class="text-center">Action</th>
</tr>';
$count = 0;
$content=$this->cart->contents();
foreach($content as $items){
$count++;
$output .='
<tr>
<td>'.$items["name"].'</td>
<td>'.$items["qty"].'</td>
<td>'.$items["price"].'</td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'"><i class="fa fa-times" aria-hidden="true"></i></button></td>
</tr>';
}
$output .='
<tr>
<td colspan="4" align="right">Total</td>
<td>'.$this->cart->total().'</td>
</tr>
</table>
<button type="submit" name="basket" class="btn btn-danger btn-lg basket" ><i class="fa fa-shopping-cart" aria-hidden="true"></i></button>
</div>';
if($count == 0){
$output = '<h3>Cart is Empty</h3>';
}
return $output;
}
public function basket(){
if ($cart = $this->cart->contents()){
foreach ($cart as $item){
$order_detail = array(
'tblItemsID' => $item['id'],
'tblLoginID' => $this -> session -> userdata('user_id'),
'Qty' => $item['qty'],
'price' => $item['price'],
'total' => $item['subtotal']
);
$this->db->insert('tblShoppingCart', $order_detail);
}
}
}
}
Note:In product_controller.php i coded button to copy cart items to another table. on button click event i wrote in jquery ajax below
jquery Ajax:
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id=$(this).data("productid");
var product_name=$(this).data("productname");
var product_price=$(this).data("price");
var quantity=$('#' + product_id).val();
if(quantity != '' && quantity >0)
{
$.ajax({
url:"<?php echo base_url();?>products/add",
method:"POST",
data:{product_id:product_id,product_name:product_name,product_price:product_price ,quantity :quantity},
success:function(data)
{
alert("Product Added into cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter Quantity");
}
});
$('#cart_details').load("<?php echo base_url();?>products/load");
$(document).on('click','.remove_inventory',function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to delete item")){
$.ajax({
url:"<?php echo base_url();?>users/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product remove fromm cart");
$('#cart_details').html(data);
}
});
}else{
return false;
}
});
$(document).on('click','#clear_cart',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/clear",
success:function(data)
{
alert("Are you sure you want clear cart?");
$('#cart_details').html(data);
}
});
}
else{
return false;
}
});
$(document).on('click','.basket',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location="users/basket";
}
});
}
else{
return false;
}
});
});
</script>
----------
Use this code on your needed redirect place:
where you will retrieve the response via ajax success response (date);
before that you will return the value in server side which mean controller.
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
location.href = data.url_path;
}
});
Use window.location.href
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location.href="<?php echo base_url();?>users/basket";
}
});
after ajax success just write.
window.location.href="redirect_location_name";

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