How to change data in DataTable using select option - javascript

Front datatable
this is front end of datatable
I want to change datatable data from select option. first time it's working after change to other category display error.
DataTables warning: table id=tblviewstock - Cannot reinitialise DataTable
<table id="tblviewstock" class="table table-striped " >
<thead>
<tr>
<th>Batch ID</th>
<th>Product ID</th>
<th>selling price</th>
<th>Quantity</th>
<th>Receive Date</th>
</tr>
</thead>
<tbody id="stockBody" style="font-size: 13px">
</tbody>
</table>
javascript
$("#stock_cat").change(function () {
var cat_id = $(this).val();
var dataTable = $("#tblviewstock").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "lib/mod_stock.php?type=viewStock&catid="+cat_id,
"type": "POST"
},
"columns": [
{"data": "0"},
{"data": "1"},
{"data": "2"},
{"data": "3"},
{"data": "4"},
]
});
});
mod_view.php - function view_stock()
this file is mod-view.php
function viewStock(){
$catid = $_GET['catid'];
$table ='tbl_products';
$primaryKey ='prod_id';
$where = "cat_id='$catid'";
$columns = array(
array( 'db' => 'prod_id', 'dt'=> 0),
array( 'db' => 'prod_img', 'dt'=> 1),
array( 'db' => 'prod_name', 'dt'=> 2),
array( 'db' => 'prod_modal', 'dt'=> 3),
array( 'db' => 'prod_color', 'dt'=> 4),
);
require_once('config.php');
$host = Config::$host ;
$user = Config::$db_uname ;
$pass = Config::$db_upass ;
$db = Config::$db_name ;
$sql_details = array(
'user' => $user,
'pass' => $pass,
'db' => $db,
'host' => $host
);
require('ssp.class.php');
echo json_encode(
SSP::complex($_POST, $sql_details, $table, $primaryKey, $columns,null,$where )
);
}

The Datatables cannot be reinisialised. (i.e the options cannot be set twice for the same table). You can try and destroy the table and recreate it once a new category is selected. Perhaps try:
var dataTable;
var i = 0;
$("#stock_cat").change(function () {
if(++i > 1) dataTable.destroy();
var cat_id = $(this).val();
dataTable = $('#tblviewstock').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "lib/mod_stock.php?type=viewStock&catid="+cat_id,
"type": "POST"
},
"columns": [
{"data": "0"},
{"data": "1"},
{"data": "2"},
{"data": "3"},
{"data": "4"},
]
});
});

Related

Server-side processing DataTables

I'm trying to dynamically load data into a table, but on each page all records are loaded at once.
my html:
<table cellspacing="0" class="display cell-border table table-sm table-striped table-bordered" width="100%" id="audience">
<thead>
<tr>
<th>Корпус</th>
<th>Этаж</th>
<th>Комната</th>
<th>Тип</th>
<th>Подразделение</th>
<th>Мест</th>
<th>Компьютерных мест</th>
<th>Действия</th>
</tr>
</thead>
</table>
js
<script>
$(document).ready(function() {
var table = $('#audience').DataTable(
{
"serverSide": true,
"processing": true,
"ajax": '/ajax/audience/zxv',
"data": JSON,
"columns": [
{ "data": "Корпус"},
{ "data": "Этаж"},
{ "data": "Комната"},
{ "data": "Тип"},
{ "data": "Подразделение"},
{ "data": "Мест"},
{ "data": "Компьютерных мест"},
{ "data": "Действия"}
],
language: tables_lang,
pageLength: 10,
orderCellsTop: true,
fixedHeader: true,
dom: 'l<"toolbar">frtip',
initComplete: function(){
$("div.toolbar")
.html('<button class="btn btn-success ml-3 add_audience">Добавить</button');
}
});
$('#audience thead tr').clone(true).appendTo( '#audience thead' );
$('#audience thead tr:eq(1) th').each( function (i) {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Поиск" />' );
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
} );
} );
table.state.clear();
table.draw();
});
</script>
php
if($request->hasValue("zxv")){
//i call the function to find out which page is now
$draw = $audienceHome->getDrawDatatables();
$data = array(
'draw' =>($draw),
'recordsTotal' =>("680"),
'recordsFiltered' =>("680"),
'data'=>
array()
);
//filled in the data from the DB
//i just get data from database using sql query and put it in array
$arr = $audienceHome->tesr();
$data['data'] = $arr;
echo json_encode($data);
}
what do i getting in json:
the table simply displays all the records at once, as well as when switching the page, regardless of how much I put 10,25,50
what should I do? so that the records are loaded gradually? Thanks in advance!

Datatables (Row Details): Uncaught TypeError: Cannot read property 'style' of undefined

im trying to implement the datatables row details
this is my table that has an id of "user_datas"
<table id="user_datas" class="table table-bordered table-striped" width="100%">
<thead>
<tr>
<th>NAME</th>
<th>SEX</th>
<th>BIRTHDATE</th>
<th>AGE</th>
</tr>
</thead>
</table>
this is the code that comes from the datatable documentation which im trying to implement
function format ( d ) {
return 'Name: '+d.name+'<br>'+
'Gender: '+d.sex+'<br>'+
'The child row can contain any data you wish, including links, images, inner tables etc.';
}
$(document).ready(function() {
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"../controller/fetch_senior_citizen.php",
type:"POST"
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "name" },
{ "data": "sex" },
{ "data": "birthdate" },
{ "data": "age" }
],
"order": [[1, 'asc']]
});
// Array to track the ids of the details displayed rows
var detailRows = [];
$('#user_datas tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dataTable.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
dataTable.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
});
and this is some of my code from fetch_senior_citizen.php
foreach($result as $row)
{
$name = clean($row["f_name"])." ".clean($row["m_name"])." ".clean($row["l_name"]);
$sub_array = array();
$sub_array["id"] = $row['id'];
$sub_array["name"] = $name;
$sub_array["sex"] = strtoupper($row["sex"]);
$sub_array["birthdate"] = $row["birthdate"];
$sub_array["age"] = $row["age"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rowsz,
"recordsFiltered" => get_total_all_records4(),
"data" => $data
);
echo json_encode($output, JSON_PRETTY_PRINT);
the error that im currently facing is Uncaught TypeError: Cannot read property 'style' of undefined but if i remove this code
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
}
Everythings work fine. But my table doesnt have row details
Problem solved! i just forgot to put an empty th on thead

How to do data tables in codeigniter?

I am fetching records from database and converting data into json array. I am getting json response correctly. but table shows no entry in my view.. please see once . Thanks.
my controller
function test() {
$list = $this->get_data_model->get_apartment_details();
$data = array();
$no = $_POST['start'];
foreach ($list as $apartments) {
$no++;
$row = array();
$row[] = $no;
$row[] = $apartments->a_id;
$row[] = $apartments->a_name;
$data[] = $row;
}
$output = array(
"draw" => 5,
"recordsTotal" => 2,
"recordsFiltered" => 1,
"data" => $data
);
echo json_encode($output);//
}
my view
<section class="tab-pane fade in active" id="newPanel">
<table style='width:100%'' class='table' id='example'>
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Activate </th>
<th> Edit </th>
</tr>
</thead>
</table>
</section>
my ajax call
$('#example').DataTable( {
"processing" : true,
"serverSide" : true,
"ajax" : {
"type" : "POST",
"url": "<?php echo base_url("apartments/test");?>",
"dataSrc" : ""
},
"columns": [
{ "data": "a_id"},
{ "data": "a_name" }
],
"dom": 'Bfrtip',
"buttons": [
{
"extend": 'copyHtml5',
"exportOptions": {
"columns": ':contains("Office")'
}
},
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
Your Table ID attribute and your ajax call id attribute is different. hope below code will help you.
$('#newPanel').DataTable( {
"processing" : true,
"serverSide" : true,
"ajax" : {
"type" : "POST",
"url": "<?php echo base_url("apartments/test");?>",
"dataSrc" : ""
},
"columns": [
{ "data": "a_id"},
{ "data": "a_name" }
],
"dom": 'Bfrtip',
"buttons": [
{
"extend": 'copyHtml5',
"exportOptions": {
"columns": ':contains("Office")'
}
},
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );

Datatables Date and Time Input

I'm trying to use the date and time input in datatables used here https://editor.datatables.net/examples/dates/datetime.html
This is what I've tried
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery-3.1.1.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/materialize.min.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery.dataTables.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/moment.js');?>"></script>
<script type="text/javascript">
//use a global for the submit and return data rendering in the examples
var editor;
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
table: '#receivablesLogs',
fields: [ {
label: 'Date:',
name: 'date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
},
{
label: 'Invoice Number:',
name: 'invoice_number'
},
{
label: 'Customer Name:',
name:'customer_name'
},
{
label: 'Total Amount:',
name: 'total_amount'
},
{
label: 'Due Date:',
name: 'due_date'
type: 'datetime',
def: function () { return new Date(); },
format: 'MM-DD-YYYY',
fieldInfo: 'US style m-d-y date input'
}
]
} );
$('#receivablesLogs').DataTable( {
dom: 'Bfrtip',
columns: [
{data: 'date'},
{data: 'invoice_number'},
{data: 'customer_name'},
{data: 'total_amount'},
{data: 'due_date'}
],
select: true,
order: [[ 0, 'asc' ]],
bFilter: false,
bLengthChange: false,
paging: false,
bFiler: false
});
});
</script>
and here is my table
<table id="receivables" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Invoice Number</th>
<th>Customer Name</th>
<th>Total Amount</th>
<th>Due Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>03/31/2014</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
<tr>
<td>02/28/2015</td>
<td>12456</td>
<td>Customer One</td>
<td>160,000.00</td>
<td>04/25/2015</td>
</tr>
</tbody>
</table>
But I don't know where I went wrong. I imported the correct js files but it doesn't display correctly. This is the output that I'm getting
Also I don't get what this line ajax: '../php/datetime.php' is for. I don't see what is the datetime.php that the documentation is referring to.
This is my first time trying datatables so I don't know where I did wrong. I already tried the basic creation of datatables and it worked but I had a problem when I tried to incorporate the date and time input in my codes.
UPDATE 1: There exists a server side script like this in the documentation
<?php
/*
* Example PHP implementation used for date time examples
*/
// DataTables PHP library
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Options,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'users' )
->fields(
Field::inst( 'first_name' ),
Field::inst( 'last_name' ),
Field::inst( 'updated_date' )
->validator( 'Validate::dateFormat', array(
'empty' => false,
'format' => 'm-d-Y g:i A'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'm-d-Y g:i A'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'm-d-Y g:i A',
'to' => 'Y-m-d H:i:s'
) ),
Field::inst( 'registered_date' )
->validator( 'Validate::dateFormat', array(
'format' => 'j M Y H:i'
) )
->getFormatter( 'Format::datetime', array(
'from' => 'Y-m-d H:i:s',
'to' => 'j M Y H:i'
) )
->setFormatter( 'Format::datetime', array(
'from' => 'j M Y H:i',
'to' => 'Y-m-d H:i:s'
) )
)
->process( $_POST )
->json();
Where should I put this?
I pull this code snippet from the site you provided a link for:
$('#example').DataTable( {
dom: 'Bfrtip',
ajax: '../php/datetime.php',
columns: [
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'updated_date' },
{ data: 'registered_date' }
],
select: true,
buttons: [
{ extend: 'create', editor: editor },
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }
]
} );
Ajax is a set of techniques to load data dynamically, behind the scenes.
Some information here: https://developer.mozilla.org/en-US/docs/AJAX
The link: "../php/datetime.php" is given as an example.
datetime.php is a file you would have to actually make in php.
In this case, datetime.php runs on the back-end, and probably queries some database.

how to sum column in datatables (i'm using codeigniter)

I'm using codeigniter and datatables for my view data. But i'm stuck how to get sum column. I have 2 fields named barang_qty, and barang_qty_toko. I need to sum this and display on datatables.
This is my Controller :
function ajax_tableBarang(){
if(!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}else{
$this->load->library('datatables_ssp');
$table = 'barang';
$primaryKey = 'barang_id';
$columns = array(
array( 'db' => 'barang_id', 'dt' => 'DT_RowID' ),
array( 'db' => 'barang_kode', 'dt' => 'barang_kode' ),
array( 'db' => 'barang_type', 'dt' => 'barang_type' ),
array( 'db' => 'barang_size', 'dt' => 'barang_size' ),
array( 'db' => 'barang_qty', 'dt' => 'barang_qty'), //I want this field result from summation of barang_qty and barang_qty_toko
array( 'db' => 'barang_harga', 'dt' => 'barang_harga' ),
array( 'db' => 'barang_klasifikasi', 'dt' => 'barang_klasifikasi'),
);
$sql_details = array(
'user' => 'user',
'pass' => 'passwd',
'db' => 'pjtomato',
'host' => 'localhost'
);
$where = "";
echo json_encode(Datatables_ssp::simple($_GET, $sql_details, $table, $primaryKey, $columns, $where));
}
}
And this is my view :
<div role="tabpanel" class="tab-pane fade in active" id="tab-all">
<table id="tableAllItem" class="table table-bordered table-striped table-hover" cellspacing="0" width="100%">
<thead>
<tr class="info">
<th>#</th>
<th>Kode</th>
<th>Jenis</th>
<th>Ukuran</th>
<th>Quantity</th> // Total of quantity (summation of barang_qty + barang_qty_toko) will display here
<th>Harga</th>
<th>Klasifikasi</th>
</tr>
</thead>
</table>
And this is the javascript for datatables:
<script type="text/javascript">
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings){
return{
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
"iTotalPages": Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
};
};
var t = $('#tableAllItem').DataTable({
"processing": true,
"serverSide": true,
"ajax": "<?php echo site_url('cAdminPage/ajax_tableBarang'); ?>",
"columns": [
{ "data": "barang_kode" },
{ "data": "barang_kode" },
{ "data": "barang_type" },
{ "data": "barang_size" },
{ "data": "barang_qty"},
{ "data": "barang_harga" },
{ "data": "barang_klasifikasi" },
],
"order": [[1, 'asc']],
"rowCallback": function (row, data, iDisplayIndex){
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
Please advice,
Thanks

Categories