I am a stuck with a problem.
I am having an ajax Datatable where I need to load the data via ajax. When I implemented the code Datatable pagination and sorting is not working. No error is displayed in the console. Don't know what to do.
here is my code...........
Controller Function
public function ajaxdata(Request $request)
{
$merchants = \DB::table('merchantsummary')->lists('id');
$queryBuilder = OrderQueueModel::take($request->input('length'))
->skip($request->input('start'))->select('order_queue.qid','order_queue.qorder_no','order_queue.created_at','customer.first_name','customer.last_name','merchant_queue_order.created_at as merchant_order_time')
->join('customer','customer.id','=','order_queue.customerid')
->join('merchant_queue_order','order_queue.qid','=','merchant_queue_order.order_queue_id')
->groupBy('merchant_queue_order.order_queue_id');
$orders = $queryBuilder->get();
$data = array();
$i=1;
foreach($orders as $order):
$merchant = MerchantOrderQueueModel::select('merchantsummary.merchant_name','merchant_queue_order.order_queue_id')
->join('merchantsummary','merchantsummary.id','=','merchant_queue_order.merchant_id')
->WHERE('merchant_queue_order.order_queue_id',$order->qid)
->get();
$merchList = '';
foreach($merchant as $mer):
if($merchList!=''){
$merchList .= ', ';
}
$merchList .= $mer->merchant_name;
endforeach;
$data[] = [ $i,
$order->qorder_no,
ucfirst($order->first_name).ucfirst($order->last_name),
date('d-m-Y H:i A', strtotime($order->created_at)),
date('d-m-Y H:i A', strtotime($order->merchant_order_time)),
$this->dateDifference($order->merchant_order_time,$order->created_at),
$merchList,
'</i> View',
];
$i++;
endforeach;
$totaldata = OrderQueueModel::count();
$totalfiltered = $orders->count();
$json_data = array(
"draw" => intval( $_REQUEST['draw'] ),
"recordsTotal" => intval( $totaldata ),
"recordsFiltered" => intval( $totalfiltered ),
"data" => $data
);
echo json_encode($json_data);
}
TableAjax.js
var orderRecords = function () {
var grid = new Datatable();
grid.init({
src: $("#order_ajax"),
onSuccess: function (grid) {
// execute some code after table records loaded
},
onError: function (grid) {
// execute some code on network or other general error
},
onDataLoad: function(grid) {
// execute some code on ajax data load
},
loadingMessage: 'Loading...',
dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js).
// So when dropdowns used the scrollable div should be removed.
//"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>",
"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.
"lengthMenu": [
[5,10, 20, 50, 100],
[5,10, 20, 50, 100] // change per page values here
],
"pageLength": 5, // default record count per page
"serverSide": true,
"columnDefs":[
{ // set default column settings
'orderable': true, 'targets': [0] },
{ "searchable": true, "targets": [0] },
],
"ajax": {
"url": "order/data", // ajax source
},
"order": [
[1, "asc"]
]// set first column as a default sort by asc
}
});
// handle group actionsubmit button click
grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
e.preventDefault();
var action = $(".table-group-action-input", grid.getTableWrapper());
if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
grid.setAjaxParam("customActionType", "group_action");
grid.setAjaxParam("customActionName", action.val());
grid.setAjaxParam("id", grid.getSelectedRows());
grid.getDataTable().ajax.reload();
grid.clearAjaxParams();
} else if (action.val() == "") {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'Please select an action',
container: grid.getTableWrapper(),
place: 'prepend'
});
} else if (grid.getSelectedRowsCount() === 0) {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'No record selected',
container: grid.getTableWrapper(),
place: 'prepend'
});
}
});
}
Need Help !! Waiting for the response..
The easiest way to apply server side data-table is:
Jquery:
$(document).ready(function() {
$('#data_table').dataTable({
"sServerMethod": "POST",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "get_data.php"
});
});
Php: get_data.php
$start = $_REQUEST['iDisplayStart']; // to handle pagination
$length = $_REQUEST['iDisplayLength']; // to handle pagination
$sSearch = $_REQUEST['sSearch']; // for searching
$col = $_REQUEST['iSortCol_0'];
$arr = array(0 => 'id', 1 => 'first_name', 2 => 'last_name', 3 => 'email');
$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];
$qry = "select id, first_name, last_name, email, position, office from datatables_demo where (first_name LIKE '%".$sSearch."%' or last_name LIKE '%".$sSearch."%' or email LIKE '%".$sSearch."%') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
$qry = "select count(id) as count from datatables_demo";
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$iTotal = $row['count'];
}
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data)) {
foreach ($data as $item) {
$rec['aaData'][$k] = array(
0 => $item['id'],
1 => '<span id="'.$item['id'].'" name="first_name" class="editable">'.$item['first_name'].'</span>',
2 => '<span id="'.$item['id'].'" name="last_name" class="editable">'.$item['last_name'].'</span>',
3 => '<span id="'.$item['id'].'" name="email" class="editable">'.$item['email'].'</span>',
4 => '<span id="'.$item['id'].'" name="position" class="editable">'.$item['position'].'</span>',
5 => '<span id="'.$item['id'].'" name="office" class="editable">'.$item['office'].'</span>'
);
$k++;
}
}
echo json_encode($rec);
Its a little bit tough to understand the code on first time, but it will render full functional server side data-table
Related
This question has been asked already but it is not solving my specific query. What I am trying to achieve is whenever a user inputs the pincode, via AJAX I am sending the pincode to PHP and returning the results with that pincode. If a single area is mapped to a particular pincode then my code works. But if there are multiple areas with same pincode then my code breaks. I have tried multiple ways. I have even tried this: Link
Here is my code
$('.input-pc').on('keyup change', function(){
PincodeId = $(this).attr('id');
PincodeVal = $("#" + PincodeId).val();
checkPincodeLength = PincodeVal.length;
if(checkPincodeLength == 6){
$('#' + PincodeId).next().next('.invalid-feedback').html('');
$.ajax({
url: "../../auth/regrequest.php",
type: "POST",
data: 'current_pincode='+PincodeVal,
dataType: 'JSON',
cache: false,
success: function(data){
console.log('pc: '+data);
$.each(data, function(index, val) {
console.log(val);
})
}
});
}else{
$('#' + PincodeId).next().next('.invalid-feedback').html('<span><i class="fa fa-exclamation-circle" aria-hidden="true"></i> Pincode must be of 6 digits</span>');
}
});
I have even tried removing the dataType and parsed the data using JSON.parse. This too did not work.
My PHP code looks like this
if(isset($_POST['current_pincode']) && !empty($_POST['current_pincode'])){
$current_pincode = $_POST['current_pincode'];
$query26 = $dbc->prepare("SELECT a.area_id, a.city_id, a.state_id, b.state_name, c.city_name, d.area_name FROM pincodes a, states b, cities c, areas d WHERE a.pincode_code = ? AND a.state_id = b.state_id AND a.city_id = c.city_id AND a.area_id = d.area_id GROUP BY area_id ORDER BY area_id");
$query26->bindParam(1, $current_pincode);
$query26->execute();
$citystate = '';
$city_id = '';
//$citystatearray = array(
// 'CityState' => array(),
//);
//$i = 0;
//while ($getcitystate = $query26->fetch(PDO::FETCH_ASSOC)){
// $citystatearray['CityState'][$i++] = $getcitystate;
// echo json_encode($citystatearray);
// }
foreach($query26 AS $getcitystate){
// $state_id = $getcitystate['state_id'];
// $state_name = $getcitystate['state_name'];
// $city_id = $getcitystate['city_id'];
// $city_name = $getcitystate['city_name'];
// $area_name = $getcitystate['area_name'];
// $rowCount = $query26->rowCount();
// //$citystate .= $area_name.',';
// //$pct = $getcitystate['pincodetime'];if(count($area_name) == 1){echo 'only one';}else{echo 'more than 1';}
if($rowCount == 1){
// $citystate =
// array(
// 'current_pincode' => $current_pincode,
// 'state_id' => $state_id,
// 'state_name' => $state_name,
// 'city_id' => $city_id,
// 'city_name' => $city_name,
// 'area_name' => $area_name,
// 'rowcount' => $rowCount
// );
}else{
$citystate .=
array(
'current_pincode' => $current_pincode,
'state_id' => $state_id,
'state_name' => $state_name,
'city_id' => $city_id,
'city_name' => $city_name,
'area_name' => array('area_name_inner' => $area_name),
'area_name' => $area_name,
'rowcount' => $rowCount
);
}
//echo $citystate;
}echo json_encode(
array(
'citystate' => $citystate
)); //echo json_encode(
// array(
// 'citystate' => $citystate
// ));//echo $citystate;
//echo $city_id;
// echo $citystate1 = $city_id.','.$rowCount.','.$citystate;
}
I have not removed the comments to show the different ways i tried to output the data but in vain. Any help would be highly appreciated. Thanks!
I am new to datatables and I am making a website search data using datatables. But mysql data is more than 10,000. When I try to search data on my web, datatables are very long displaying data. Can anyone help me, how do I get datatables to display tables faster with large data. Thank you
PHP:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "test");
$columns = array('id', 'datetime', 'temperature', 'humidity');
$query = "SELECT id, datetime, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(datetime) BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(id LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= "GROUP BY DATE_FORMAT(datetime, '%d-%M-%Y-%H:%i:%s') ORDER BY 'id'";
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query );
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["datetime"];
$sub_array[] = $row["temperature"];
$sub_array[] = $row["humidity"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM data";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
Javascript:
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#tabel_data').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
filename: 'datatable'
},
],
"paging": false,
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
}
});
dataTable.on('draw.dt', function () {
var info = dataTable.page.info();
dataTable.column(0, { search: 'applied', order: 'applied', page: 'applied', }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + info.start;
dataTable.cell(cell).invalidate('dom');
});
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#tabel_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Date Required");
}
});
});
1) use pagination how to use pagination with PHP and mysql instead of a simple query like below.
"SELECT * FROM data";
2) Dot select * because * will select unnecessary fields also instead define column name for which you want to show data
example:
select name,page,amt from data
your final query will look like
SELECT emp_id, emp_name, emp_salary FROM employee LIMIT $offset, $rec_limit;
check the link above how to use pagination with PHP and mysql
Currently i am working on eCommerce website in that i have to display all data from database to datatable. Data is coming properly in datatable but searching, sorting and pagination is not working.If any body know solution than please help. Below is my code
Controller.php
Public function transaction_data()
{
$id = $this->session->Vendordetail['id'];
$transactionData = $this->Mdl_vendor_payment->get_order_list($id);
$requestData= $_REQUEST;
$totalData = count($transactionData);
$totalFiltered = count($transactionData);
$return_days = $this->Mdl_common->get_setting('shipping_charge');
foreach($transactionData as $transaction){
$product = $this->Mdl_common->product_id($transaction['prodouct_id']);
$data['order_id'] = $transaction['order_id'];
$data['created'] = $transaction['created'];
if($transaction['status'] == 5){
$data['status'] = '<h5><span class="label label-danger">Cancelled</span></h5>';
}else if($transaction['status'] == 4){
$data['status'] = '<h5><span class="label label-default">Return</span></h5>';
}else if($transaction['status'] == 3){
$data['status'] = '<h5><span class="label label-success">Success</span></h5>';
}else if($transaction['status'] == 2){
$data['status'] = '<h5><span class="label label-primary">Dispatch</span></h5>';
}else if($transaction['status'] == 1){
$data['status'] = '<h5><span class="label label-primary">Ready To Dispatch</span></h5>';
}else{
$data['status'] = '<h5><span class="label label-primary">Approve</span></h5>';
}
$data['price'] = '<i class="fa fa-rupee"></i> '.$transaction['price']*$transaction['qty'];
$data['settlement_price'] = '<i class="fa fa-rupee"></i> '.$transaction['settlement_price']*$transaction['qty'];
$shipping_charge = $return_days['value'] * ($transaction['qty'] * $product['weight']);
$data['shipping_charge'] = '<i class="fa fa-rupee"></i> '.$shipping_charge;
$data['commission_fee'] = ($transaction['price']*$transaction['qty'])-($transaction['settlement_price']-$transaction['qty']);
$data['payable_amount'] = ($transaction['settlement_price']*$transaction['qty'])-$shipping_charge;
$data['order'] = $transaction;
$data['product'] = $product;
$assignment_datas[] = $data;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $assignment_datas
);
echo json_encode($json_data);
die;
}
Below is the code for view file
View.php
$(document).ready(function() {
var dt = $('#datatable_example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url":"<?php echo base_url(); ?>index.php/Vendor_payment/transaction_data",
"type":"POST",
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "order_id" },
{ "data": "created" },
{ "data": "status" },
{ "data": "price" },
{ "data": "settlement_price" },
{ "data": "shipping_charge" }
],
"order": [[0, 'asc']]
} );
// Array to track the ids of the details displayed rows
var detailRows = [];
$('#datatable_example tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dt.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
// Remove from the 'open' array
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
// Add to the 'open' array
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
// On each draw, loop over the `detailRows` array and show any child rows
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
This code is work fine for me...
In view page:
<table id="user_datatable" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 5%;">ID</th>
<th>Client name</th>
<th>Mobile</th>
<th>Email</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#user_datatable').DataTable({
'pageLength': 1,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url': '<?php echo base_url(); ?>user/userList'
},
'columns': [{
data: 'id'
},
{
data: 'name'
},
{
data: 'mobile'
},
{
data: 'email'
},
{
data: 'action'
},
]
});
});
</script>
In Controller page
public function userList() {
$postData = $this->input->post();
$data = $this->Data_model->getUserList($postData);
echo json_encode($data);
}
In Model page
Set the table name in $table variable
// $table = 'clients';
Add column name whatever you add in datatable
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
function getUserList($postData=null) {
$response = array();
$table_name = 'clients';
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$searchQuery = "";
if($searchValue != ''){
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$this->db->select('count(*) as allcount');
$records = $this->db->get($table_name)->row();
$totalRecords = $records->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchValue != '')
$this->db->where($searchQuery);
$records = $this->db->get($table_name)->row();
$totalRecordwithFilter = $records->allcount;
## Fetch records
$this->db->select('*');
if($searchValue != '')
$this->db->where($searchQuery);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$records = $this->db->get($table_name)->result();
$data = array();
foreach($records as $key => $record) {
$data[] = array(
"id"=> ($key + 1),
"name"=>$record->name,
"mobile"=>$record->mobile,
"email"=>$record->email,
"action"=>"<a href='".base_url()."user/update/".$record->id."' type='button' class='btn btn-success'>Update</a><a href='".base_url()."user/delete/".$record->id."' type='button' class='btn btn-danger' style='margin-left: 5px;'>Delete</a>",
);
}
## Response
$response = array(
"draw" => intval($draw),
"recordsTotal" => $totalRecordwithFilter,
"recordsFiltered" => $totalRecords,
"data" => $data
);
return $response;
}
I'm building a forum using Code Igniter framework. I'm trying to implement Datatables server side processing. I know how to use datatables and JQuery for actions such as sorting and searching, but my database table has the potential to grow to thousands and pulling all the rows at once will not make users very happy, so I'm trying to combine both server side (Code Igniter) and client side (AJAX) processing in order to use limits and offsets. So I dug into the web and found an awesome tutorial. This is what I have:
Model: Posts_model.php
<?php
var $table = 'general_posts';
var $column_order = array(null, 'title','body','username','time','category'); //set column field database for datatable orderable
var $column_search = array('title','body','username','time','category'); //set column field database for datatable searchable
var $order = array('id' => 'desc'); // default descending order
private function get_posts_query() {
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item)
{
if($_POST['search']['value'])
{
if($i===0) // first loop
{
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if(isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_gen_posts($category) {
$this->get_posts_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->result();
}
function count_filtered_gen_posts($category) {
$this->get_posts_query();
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->num_rows();
}
public function count_all($category) {
$this->db->where(array('category' => $category, 'display' => 'true'));
$this->db->from($this->table);
return $this->db->count_all_results();
}
} ?>
Controller: Posts.php
<?php
public function __construct() {
parent::__construct();
$this->load->model('posts_model','general_posts');
}
public function posts($category) {
$data['category'] = $category;
$this->load->view('posts', $data);
}
public function posts_ajax($category)
{
$list = $this->general_posts->get_gen_posts($category);
$data = array();
foreach ($list as $post) {
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->general_posts->count_all($category),
"recordsFiltered" => $this->general_posts->count_filtered_gen_posts($category),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
} ?>
View: posts.php
<table id="table" class="table table-no-border" cellspacing="0" width="100%" style="text-align: left">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"paging": true,
"pageLength" : 10,
"lengthChange": true,
"searching": true,
"info": false,
"autoWidth": true,
"ordering": false,
"stateSave": true,
"processing": true,
"serverSide": true,
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo base_url('posts/posts_ajax/'.$category)?>",
"dataType": "json",
"type": "POST",
"data":{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
</script>
So far, everything works as expected, but it does not entirely suit my needs. Look at these lines:
foreach ($list as $post) {
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
}
I'd like the results of each row to display in ONE COLUMN, not in 5 colums. This is because I intend to use Bootstrap panel to display the result of each row, and customise it to suit my needs.
I want something like this for each result:
Post Title: bla bla bla
The body goes here
Posted in: category name
Posted by: name of poster
Time: 9th Sep, 2017 at 10: 30PM
I would like to control how each field is displayed, with stylings and formatings, such as converting the time field into something more human-readable (eg 9th Sep, 2017 at 10: 30PM). The problem is, since the loop is created inside the controller (rather than in view, which I'm used to), I do not know how to go about doing this. I know if I can get the loop between the table body tags ( here ), I can do what I want, but I don't think AJAX will appreciate it if I did (I tried it, 'he' didn't). This is my first dabble into AJAX.
EDIT: I am wondering if there is a way to use the contents of the post_ajax function inside view so that I can put the foreach loop inside the body tag of table.
So I need help. Please help! Sorry it's so long...
Follow the stapes And Get Result
Step 1 : - on view side paste below code
<table id="table_lists" class="table table-bordered table-hover table-striped datatable ">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Day</th>
<th>Holiday</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="javascript">
var t = $('#table_lists').DataTable({
"processing": true,
"serverSide": true,
"ordering": false,
"ajax": {
"url": "<?php echo admin_url('employee/lists'); ?>",
"type": "POST",
},
"columns": [
{ "data": "no" },
{ "data": "date" },
{ "data": "day" },
{ "data": "holiday" },
{ "data": "action"},
],
});
</script>
Step 2: - In Controller create function like these
public function lists(){
$json_data = $this->holiday->get_list_table();
echo json_encode($json_data);
}
Step 3: - Paste Below code in model
public function get_list_table()
{
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$start = $params['start'];
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" AND ";
$where .=" ( ";
$where .=" name LIKE '%".$params['search']['value']."%' ";
$where .=" OR DATE_FORMAT(date, \"%d-%m-%Y\") LIKE '%".$params['search']['value']."%' ";
$where .=" OR DAYNAME(date) LIKE '%".$params['search']['value']."%' ";
$where .=" )";
}
$sql = "SELECT *
FROM {$this->tbl_holiday}
WHERE 1 = 1 {$where}
ORDER BY date ASC";
$sqlTot .= $sql;
$sqlRec .= $sql;
$sqlRec .= " LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = $this->db->query($sqlTot);
$totalRecords = $queryTot->num_rows();
$queryRecords = $this->db->query($sqlRec);
$results = $queryRecords->result();
$i = ($start + 1);
if(!empty($results)) {
foreach ($results as $result) {
$actions = '<a href="javascript:void(0);" onclick="javascript: editHoliday('.$result->id.');" class="btn btn-info btn-sm">
<i class="fa fa-edit"></i>
</a>
<a href="javascript:void(0);" title="Delete" data-toggle="modal" data-target="#confirm-delete" class="btn btn-danger btn-sm" data-href="'.admin_url('holiday/delete/'.$result->id).'">
<i class="fa fa-trash"></i>
</a>';
$data[] = array(
'no' => $i,
'date' => date('d-m-Y', strtotime($result->date)),
'day' => date('l', strtotime($result->date)),
'holiday' => $result->name,
'action' => $actions,
);
$i++;
}
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
return $json_data;
}
i'm beginner in codeigniter. i work using cart library from codeigniter and it's work fine. but i have another values as weight and amount (interger value) in my list cart. example when i adding a same value in twice, just qty and subtotal has increased. the weight and amount just update where i Last input not calculate from old value with new value. how i can solved this..?
i'm using CI v3.1 and datatables for show the list cart,
sorry for my bad english language. best regards :)
here my controller cart
//adding to cart list
public function addbarang()
{
$data = array(
'id' => $this->input->post('id_barang'),
'price' => str_replace('.', '', $this->input->post('harga_barang')),
'qty' => $this->input->post('qty'),
'unit' => $this->input->post('j-unit'),
'name' => $this->input->post('nama_barang'),
'nama_jenis' => $this->input->post('j-nama_jenis'),
'id_jenis' => $this->input->post('j-id_jenis'),
'options' => array('j-berat' => $this->input->post('j-weight'),'j-amount' => $this->input->post('j-amount'))
);
$insert = $this->cart->insert($data);
echo json_encode(array("status" => TRUE));
//echo"<pre>";
//print_r($this->cart->contents());
// echo"<pre>";
}
//show cart list in datatables
public function ajax_list_transaksi()
{
$data = array();
$no = 1;
foreach ($this->cart->contents() as $items){
$row = array();
$row[] = $no;
$row[] = $items["id"];
$row[] = $items["name"];
$row[] = $items["id_jenis"];
$row[] = $items["nama_jenis"];
$row[] = $items["qty"];
$row[] = $items["unit"];
$row[] = $items["options"]["j-berat"];
$row[] = $items["options"]["j-amount"];
$row[] = 'Rp. ' . number_format( $items['price'],
0 , '' , '.' ) . ',-';
$row[] = 'Rp. ' . number_format( $items['subtotal'],
0 , '' , '.' ) . ',-';
//add html for action
$row[] = '<a href="javascript:void(0)" style="color:rgb(255,128,128); text-decoration:none" onclick="deletebarang('
."'".$items["rowid"]."'".','."'".$items['subtotal']."'".')"> <i class="fa fa-close"></i> Delete</a>';
$data[] = $row;
$no++;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
my js to show and adding value cart list
//the js to show cart list in html
var table;
$(document).ready(function() {
table = $('#table_transaksi').DataTable({
"paging": true,
"ordering": false,
"info": false,
"searching": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?= site_url('Master_rabp/ajax_list_transaksi')?>",
"type": "POST"
},
"columnDefs": [{
"targets": [ 0,1,2,3,4,5,6 ],
"orderable": false,
}],
});
});
function reload_table()
{
table.ajax.reload(null,false);
}
//the js for adding new cart value
function addbarang()
{
var id_barang = $('#id_barang').val();
var qty = $('#qty').val();
if (id_barang == '') {
$('#id_barang').focus();
}else if(qty == ''){
$('#qty').focus();
}else{
$.ajax({
url : "<?= site_url('Master_rabp/addbarang')?>",
type: "POST",
data: $('#form_transaksi').serialize(),
dataType: "JSON",
success: function(data)
{
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data');
}
});
$('.reset').val('');
};
}
function deletebarang(id,sub_total)
{
// ajax delete data to database
$.ajax({
url : "<?= site_url('Master_rabp/deletebarang')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}