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!
Related
I am using to Jquery datables to create a table with row details . Everything working fine Only the number of entries
The current logic is counting the parents row + child rows. I want to count only parents rows which are 4. My result should be Showing 1 to 10 of 4 entries.
In my Json file, I have recordsTotal: 16 which is the total rows parents + child. When I change to 4 which is number of parents rows the table will show me only first record (Ticket id 1 + its 3 child rows ) as it's counted as 4 entries.
Any suggestions please how can I update ? Thank you.
$(document).ready(function() {
function format ( d ) {
d.Items.sort(function compare(a,b) {
if (a.Line_No < b.Line_No)
return -1;
if (a.Line_No > b.Line_No)
return 1;
return 0;
});
var x = '<table class="nowrap table table-bordered table-hover" cellspacing="0" width="100%"><thead><tr><th>Line No</th><th>Line Level Issue</th><th>Created Date</th><th>Created By</th></tr></thead><tbody>' ;
$.each(d.Items, function( index, value ) {
x += '<tr><td>' + d.Items[index].Line_No + '</td><td>' + d.Items[index].Line_Level_Issue + '</td><td>' + d.Items[index].Created_Date + '</td><td>' + d.Items[index].Created_By + '</td></tr>';
});
x +='</tbody></table>';
return x;
}
var dt = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"deferRender": true,
"lengthChange": true,
"pageLength": 10,
"language": { "emptyTable": "No matching records found",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"zeroRecords": "No matching records found" },
"ajax": "https://api.myjson.com/bins/vwjfc",
"columns": [
{
"class": "details-control",
"data": "Ticket_id"
,render : function(data, type, row) {
return ' ' + data;
}
},
{ "data": "Order_Level_Issue" },
{ "data": "Geo" },
{ "data": "Region" },
{ "data": "Territory" },
{ "data": "Market" },
{ "data": "Country" },
{ "data": "SoldTo_Number" },
{ "data": "SoldTo_Name" },
{ "data": "Order_Numer" }
],
"order": [[0, 'asc'],[1, 'asc']]
} );
var detailRows = [];
$('#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();
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
td.details-control {
background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center left;
cursor: pointer;
}
tr.details td.details-control {
background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center left;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>
<table id="example" class="nowrap table table-hover table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>TicketT id</th>
<th>Order Level Issue</th>
<th>Geo</th>
<th>Region</th>
<th>Territory</th>
<th>Market</th>
<th>Country</th>
<th>SoldTo Number</th>
<th>SoldTo Name</th>
<th>Order Numer</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Ticket id</th>
<th>Order Level Issue</th>
<th>Geo</th>
<th>Region</th>
<th>Territory</th>
<th>Market</th>
<th>Country</th>
<th>SoldTo Number</th>
<th>SoldTo Name</th>
<th>Order Numer</th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
I assume the problem was not dataTables at all but your ajax call, since you are using serverSide your server side is the one who sends the data the table will display including the total of records so in your ajax response you have:
{draw: 1, recordsTotal: 16, recordsFiltered: 16, data: Array(4)}
So all you have to do is work in your server side script in order the reflect the expected output.
Hope it helps
I'm trying to add an index column like this example ( https://datatables.net/examples/api/counter_columns.html ), in my table. I try to implement the code from the example to my program, but the results don't appear. How do I add an index column like the example, to my table ?
thank you
Table :
<table id="order_data">
<thead >
<tr >
<th style="text-align:center;" width="21%">Number</th>
<th style="text-align:center;" width="21%">Datetime </th>
<th style="text-align:center;" width="19%">Temp</th>
<th style="text-align:center;" width="21%">Humidity</th>
</tr>
</thead>
</table>
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 = $('#order_data').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
title: '<h3 align ="center">Monitoring</h3>',
text: '<i class="fa fa-pencil"></i>',
messageTop: '<p align ="center"><strong>PDF</strong> created by PDFMake with Buttons for DataTables.</p>'
},
{
extend: 'pdfHtml5',
customize: function (doc) {
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
},
title: 'Monitoring',
titleAttr: 'PDF',
text: 'PDF',
}
],
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
"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
},
},
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#order_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
//$("#tabel").show();
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Both Date is Required");
}
});
dataTable.on( 'order.dt search.dt', function () {
dataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
The example you're referencing isn't using server side processing. Rather it's assuming a static data source. You have serverSide: true and using an AJAX request to retrieve the data from a source so there are a couple of ways to handle this:
1) Use column render to generate the index value after the data is retrieved:
{
"sName": "Index",
"render": function (data, type, row, meta) {
return meta.row; // This contains the row index
}
}
2.) Add the index value to your data source and retrieve it along with your url:"fetch.php" request. Though this would actually act more like a unique ID and less like row numbering.
There is also an api call for row().index() that you could leverage in a number of ways.
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
Sorry for the bad title. I am new to Rails and Javascript. I setup a DataTable using child rows following the DataTables documentation using a single ajax call to a JSON file.
I got that all working I now want to use my Rails controller to get the JSON from a Mongo DB. I also have that part working. What I am confused about is probably very simple and I am used to building a Rails table with active record BUT here I had a separate javascript called tests.js with my DataTable definition and the ajax call to a file. Can I now just pass in the JSON from the View somehow? I am not sure how to switch from the ajax call to using the JSON I now have from my controller
$(document).ready(function() {
var table = $('#queryone_table').DataTable( {
"ajax": "/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "transactionType" },
{ "data": "collationId" },
{ "data": "licensePlate" },
{ "data": "description" },
{ "data": "startDate" },
{ "data": "FeedComplete" },
{ "data": "RepoComplete" },
{ "data": "feedProcessingDuration" },
{ "data": "completeDuration" }
],
"order": [[1, 'asc']]
} );
Objects.txt I would now like to be a var from my View? With active record and MySQL I would build the table in the view looping over a dataset from controller but with the child row code already done in javascript I would like to leave that.
full javascript code
$(document).ready(function() {
var table = $('#queryone_table').DataTable( {
"ajax": "/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "transactionType" },
{ "data": "collationId" },
{ "data": "licensePlate" },
{ "data": "description" },
{ "data": "startDate" },
{ "data": "FeedComplete" },
{ "data": "RepoComplete" },
{ "data": "feedProcessingDuration" },
{ "data": "completeDuration" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#queryone_table tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
function format ( d ) {
var foo = '<table id="queryinner_table" cellpadding="5" cellspacing="2" border="1" style="padding-left:50px;" class="table table-striped table-bordered table-hover table-condensed dataTable no-footer sub-table">';
// loop over table rows
var trow = "";
for (var i=0; i< d.nextrow.length; i++) {
var foo2 = '<tr>'+
'<td>Transaction Step:</td>'+
'<td>'+d.nextrow[i].transactionStep+'</td>'+
'<td>'+d.nextrow[i].elapsedSeconds+'</td>'+
'</tr>'
trow = trow + foo2
} //for loop
var foo2 = '</table>';
var res = foo.concat(trow);
res = res.concat(foo2);
return res;
}
This was poorly worded I have started a new project and will ask a few questions based on that code rather than rewrite this one.
I'm struggeling to make a static column with 2 buttons that trigger 2 links with dynamic data. I managed to make 1 button work but i can't make the other. I tried adding an id to each one and call different functions for each one but it seems it's only working with $(\'#example tbody \') and not ($(\'#customID \').
Here is my js:
<script type="text/javascript">
$(document).ready(function() {
var table = $(\'#example\').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "app/server_processing.php",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Edit</button> <button>Delete</button>"
} ]
} );
$(\'#example tbody \').on( \'click\', \'button\', function () {
var data = table.row( $(this).parents(\'tr\') ).data();
window.location.href = "index.php?categ=edit&id="+ data[0];
} );
} );
</script>
I fixed it
<script type="text/javascript">
$(document).ready(function() {
var table = $(\'#example\').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "app/server_processing.php",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button id="edit">Edit</button> <button id="delete">Delete</button>"
} ]
} );
$(\'#example tbody \').on( \'click\', \'#edit\', function () {
var data = table.row( $(this).parents(\'tr\') ).data();
window.location.href = "index.php?categ=edit&id="+ data[0];
} );
$(\'#example tbody \').on( \'click\', \'#delete\', function () {
var data = table.row( $(this).parents(\'tr\') ).data();
window.location.href = "index.php?categ=delete&id="+ data[0];
} );
} );
</script>