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'
]
} );
} );
Related
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!
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"},
]
});
});
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
Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?
I have a working datatable that is retrieving data from a file :
I want to group row, something like this :
https://datatables.net/examples/advanced_init/row_grouping.html
My goal would to have my datatable to look like this, grouping row by the date (last column), but even looking at the code, I have trouble to make it work. I'd like some help to make that work if you could.
Here is the code of my datatable :
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo base_url()."assets/files/data/data.txt"; ?>" ,
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" }
],
"order": [[ 0, "desc" ]],
"responsive": true
} );
} );
You should use drawCallback function.
Try.
$(document).ready(function() {
$('#datatable').DataTable({
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" },
{ "data": "extra" }
],
"order": [[ 4, "desc" ]],
"responsive": true,
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(4, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="8" style="BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + 'GRUPO ....' + group + '</td></tr>'
);
last = group;
}
});
}
});
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/13/
It seems you get the error when outputting the url by PHP into the Javascript.
Try this instead:
ajax: "<?php echo base_url() . 'assets/files/data/data.txt'; ?>"
Not the single-qoutes in the PHP-code.