I have a data table with twelve(12) columns. I am using PHP to populate the data inside my data table. My problem is I can populate the data table but I am getting "Cannot reinitialize data table" error but I only initialize my table once. How can I fix this and avoid this problem in the future?
Here is my data table using javascript I am using serverside processing to get and populate my data table:
table = [
{ "width": "80px", "targets": 0 },
{ "width": "120px", "targets": 1 },
{ "width": "120px", "targets": 2 },
{ "width": "120px", "targets": 3 },
{ "width": "120px", "orderable": false, "targets": 4 },
{ "width": "120px", "targets": 5 },
{ "width": "100px", "targets": 6 },
{ "width": "110px", "targets": 7 },
{ "width": "150px", "orderable": false, "targets": 8 },
{ "width": "150px", "orderable": false, "targets": 9 },
{ "width": "150px", "orderable": false, "targets": 10 },
{ "width": "150px", "orderable": false, "targets": 11 }
];
var table = $('#activities-table').DataTable({
"searching": { "regex": true },
"bLengthChange": false,
"scrollY":"500px",
"scrollX":"300px",
"scrollCollapse": true,
"paging": false,
"autoWidth": false,
"processing": true,
"serverSide": true,
"autoWidth": true,
"ajax": {
url: "activities-data.php",
type: "POST",
"dataType": "json",
data: {salesman:salesman, startdate:startdate, enddate:enddate, supervisor:supervisor},
"complete": function(response) {
console.log(response);
}
},
"columnDefs": table,
"language": {
"emptyTable": "No data available in table",
"zeroRecords": "No data available in table",
"info": "Showing <b>_START_</b> to <b>_END_ of _TOTAL_</b> entries",
"paginate": {
"first": "First",
"last": "Last",
"next": "Next",
"previous": "Previous"
},
search: "_INPUT_",
searchPlaceholder: "Search..."
},
dom: 'Bfrtip',
buttons: [
'csv', 'excel', 'pdf'
]
});
And here is how I populate my data table using PHP
Note: This code will only return one(1) data
$salesman = $_POST["salesman"];
$supervisor = $_POST["supervisor"];
$startdate = $_POST["startdate"];
$enddate = $_POST["enddate"];
$request = $_REQUEST;
$whereCondition = "";
$sqlTotal = "";
$sqlRecord = "";
$columns = array(
0 => 'tblCaf.CAFNo',
1 => 'EmployeeName',
2 => 'CustomerName',
3 => 'ContactPerson',
4 => 'Activity',
5 => 'tblCaf.ActivityDate',
6 => 'tblCaf.StartTime',
7 => 'tblCaf.EndTime',
8 => 'tblCaf.StartLocation',
9 => 'tblCaf.EndLocation',
10 => 'tblCaf.OtherConcern',
11 => 'tblCaf.Remarks'
);
if(!empty($request['search']['value'])){
$whereCondition .= " AND
(tblCaf.CAFNo LIKE '%".$request['search']['value']."%'
OR EmployeeName.FileAs LIKE '%".$request['search']['value']."%'
OR CustomerName.FileAs LIKE '%".$request['search']['value']."%'
OR ContactPerson.FileAs LIKE '%".$request['search']['value']."%')";
}
$sql = "SELECT TOP 50 EmployeeName.FileAs AS Emp, CustomerName.FileAs AS CUS, ContactPerson.FileAs AS CP, tblCaf.CAFNo, tblCaf.CAFDate, tblCaf.StartTime, tblCaf.EndTime, tblCAF.StartLocation, tblCAF.EndLocation, tblCaf.OtherConcern, tblCaf.Remarks
FROM tblCaf
LEFT OUTER JOIN tblContacts AS EmployeeName ON EmployeeName.ContactID = tblCaf.EmployeeID
LEFT OUTER JOIN tblContacts AS CustomerName ON CustomerName.ContactID = tblCaf.CustomerID
LEFT OUTER JOIN tblContacts AS ContactPerson ON ContactPerson.ContactID = tblCaf.ContactPersonID
LEFT OUTER JOIN tblSalesmanSupervisor ON tblSalesmanSupervisor.SalesmanID = tblCaf.EmployeeID
WHERE tblCaf.CAFDate BETWEEN :start AND :end";
$sqlTotal .= $sql;
$sqlRecord .= $sql;
if(isset($whereCondition) && $whereCondition != ""){
$sqlTotal .= $whereCondition;
$sqlRecord .= $whereCondition;
}
if($db_conn == "MYSQL"){
$sqlRecord .= " ORDER BY ". $columns[$request['order'][0]['column']] ." " . $request["order"][0]['dir'] . " LIMIT " . $request["start"] . " ," . $request["length"]. " ";
$sqlTotal .= " LIMIT 50";
}
else{
$sqlRecord .= " ORDER BY ". $columns[$request['order'][0]['column']] ." " . $request["order"][0]['dir'];
}
$resultTotal = $conn->prepare($sqlTotal, $cursor);
$resultTotal->bindValue(":start", $startdate);
$resultTotal->bindValue(":end", $enddate);
$resultTotal->execute();
$totalData = $resultTotal->rowCount();
$resultRecords = $conn->prepare($sqlRecord, $cursor);
$resultRecords->bindValue(":start", $startdate);
$resultRecords->bindValue(":end", $enddate);
$resultRecords->execute();
$data = array();
$activities = "";
$i = 1;
$subdata = array();
if($totalData > 0){
while($row = $resultRecords->fetch()){
$subdata[] = $row["CAFNo"];
$subdata[] = strtoupper($row["Emp"]);
$subdata[] = strtoupper($row["CUS"]);
$subdata[] = strtoupper($row["CP"]);
$multiplesql = $conn->prepare("SELECT ActivityID FROM tblCafActivity WHERE CAFNo = :caf", $cursor);
$multiplesql->bindValue(":caf", $row["CAFNo"]);
$multiplesql->execute();
$multiplecount = $multiplesql->rowCount();
if($multiplecount > 0){
while($multiplerow = $multiplesql->fetch()){
$activitysql = $conn->prepare("SELECT ActivityDescription FROM tblActivity WHERE ActivityID = :act", $cursor);
$activitysql->bindValue(":act", $multiplerow["ActivityID"]);
$activitysql->execute();
$activitycount = $activitysql->rowCount();
if($activitycount > 0){
while($activityrow = $activitysql->fetch()){
$activities = strtoupper($activityrow["ActivityDescription"]) . "<br/>";
}
}
}
}
$subdata[] = $activities;
$subdata[] = date("F j, Y", strtotime($row['CAFDate']));
$subdata[] = date("h:i:s a", strtotime($row['StartTime']));
if(empty($row['EndTime'])){
$subdata[] = "";
}
else {
$subdata[] = date("h:i:s a", strtotime($row['EndTime']));
}
$subdata[] = $row['StartLocation'];
$subdata[] = $row['EndLocation'];
$subdata[] = strtoupper($row["OtherConcern"]);
$subdata[] = strtoupper($row["Remarks"]);
$data[] = $subdata;
}
}
$json_data = array(
"draw" => intval($request['draw']),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalData),
"data" => $data
);
print json_encode($json_data);
You variable name for columns and table is same i.e "table". table is being called inside data-table initialization as well. Chanege the variable name for columnDefs to something else.
var columns= [
{ "width": "80px", "targets": 0 },
{ "width": "120px", "targets": 1 },
{ "width": "120px", "targets": 2 },
{ "width": "120px", "targets": 3 },
{ "width": "120px", "orderable": false, "targets": 4 },
{ "width": "120px", "targets": 5 },
{ "width": "100px", "targets": 6 },
{ "width": "110px", "targets": 7 },
{ "width": "150px", "orderable": false, "targets": 8 },
{ "width": "150px", "orderable": false, "targets": 9 },
{ "width": "150px", "orderable": false, "targets": 10 },
{ "width": "150px", "orderable": false, "targets": 11 }
];
var table = $('#activities-table').DataTable({
"searching": { "regex": true },
"bLengthChange": false,
"scrollY":"500px",
"scrollX":"300px",
"scrollCollapse": true,
"paging": false,
"autoWidth": false,
"processing": true,
"serverSide": true,
"autoWidth": true,
"ajax": {
url: "activities-data.php",
type: "POST",
"dataType": "json",
data: {salesman:salesman, startdate:startdate, enddate:enddate, supervisor:supervisor},
"complete": function(response) {
console.log(response);
}
},
"columnDefs": columns,
"language": {
"emptyTable": "No data available in table",
"zeroRecords": "No data available in table",
"info": "Showing <b>_START_</b> to <b>_END_ of _TOTAL_</b> entries",
"paginate": {
"first": "First",
"last": "Last",
"next": "Next",
"previous": "Previous"
},
search: "_INPUT_",
searchPlaceholder: "Search..."
},
dom: 'Bfrtip',
buttons: [
'csv', 'excel', 'pdf'
]
});
Try putting this code before your ajax call.
"destroy": true
read more on destroy here: link: https://datatables.net/reference/option/destroy
or if it fails, add this
"retrieve": true
link: https://datatables.net/reference/option/retrieve
Related
After passing json_encode variable, not able to loading "sProcessing" text before loading data. I am trying to load more than 50000 records.
Javascript Code
<script>
var data = <?php echo json_encode($data); ?>;
$(document).ready(function() {
$('#datatable').dataTable({
"aaData": data,
"bProcessing": true,
"aoColumns": [
{ "data": "submissions_dt" },
{ "data": "pettycash_dt" },
{ "data": "type" },
{ "data": "description" },
{ "data": "voucher_no" },
{ "data": "amount", className: "right" }
],
"oLanguage": {
"sProcessing": "Fetching Data, Please wait..."
},
order: [[2, 'desc']],
"lengthMenu": [[50, 100, -1], [50, 100, "All"]],
"columnDefs": [
{ "orderable": false, "targets": [0,1,2,3,4,5] },
{"targets": [ 2 ], "visible": false }
]
});
});
</script>
Unable to display the last column in DataTable
THE code works fine, but I'm not sure whats wrong in my code. The last column "DELETE" doesn't show. The code given below. Any help will be highly appreciated..
I'm using DataTable to display my records. The '$title' is the name of the page which is passed inside AJAX to get the required table.
HTML
<div class="container justify-content-center">
<div class="table-responsive-md justify-content-center">
<table id="dataTable" class="table table-striped shadow" style="width:100%">
<thead class="bg-secondary text-white">
<tr>
<th>ID</th>
<th>University</th>
<th>Code</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
JQUERY
$(document).ready(function () {
$title = $(".page-title").text().toLowerCase();
$('#dataTable').DataTable({
responsive: true,
"autoWidth": true,
"searching": true,
"paging": true,
"info": false,
"pagingType": "full_numbers",
"pageLength": 5,
"lengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]],
"bLengthChange": false,
"stateSave": true,
"bStateSave": true,
fixedHeader: {
header: true,
footer: false
},
"processing": true,
"serverSide": false,
"ajax": {
"url": "scripts/post.php",
"type": "POST",
"dataType": "json",
"dataSrc": "data",
"data": {
table: "tbl_" + $title
}
},
"rowId": "pk_int_" + $title + "ID",
"columns": [
{"data": "pk_int_" + $title + "ID"},
{"data": "txt_" + $title + "Name"},
{"data": "txt_" + $title + "Code"},
{
"data": null,
"visible": true,
"defaultContent": '<i class="far fa-edit"></i>',
"targets": -1
},
{
"data": null,
"visible": true,
"defaultContent": '<i class="far fa-trash-alt text-danger"></i>',
"targets": -1
}
],
columnDefs: [
{"title": "University Name", "targets": 1},
// {targets: [0, 1, 2, 3, 4], visible: true},
{targets: '_all', visible: true},
{
"targets": 0,
"title": "ID",
"className": "text-left",
"width": "5%"
},
{
"targets": 1,
"className": "text-left",
"width": "50%"
},
{
"targets": 2,
"className": "text-left",
"width": "25%"
},
{
"targets": [3, 4],
"className": "text-center",
"width": "10%",
"visible": true,
"bSortable": false
}
],
language: {
paginate: {
next: '<i class="fas fa-angle-right"></i>',
previous: '<i class="fas fa-angle-left"></i>',
first: '<i class="fas fa-angle-double-left"></i>',
last: '<i class="fas fa-angle-double-right"></i>'
}
}
});
});
JSON
{
"recordsTotal": 5,
"data": [{
"pk_int_universityID": "1",
"txt_universityName": "Not Available",
"txt_universityCode": "NA"
}, {
"pk_int_universityID": "2",
"txt_universityName": "Others",
"txt_universityCode": "Others"
}, {
"pk_int_universityID": "3",
"txt_universityName": "Sultan Qaboos University",
"txt_universityCode": "SQU"
}, {
"pk_int_universityID": "4",
"txt_universityName": "Oman Medical College",
"txt_universityCode": "OMC"
}, {
"pk_int_universityID": "5",
"txt_universityName": "Arabian Gulf University",
"txt_universityCode": "AGU"
}]
}
OUTPUT
I want to set the default ordering of my datatable into desc.
I tried to see the value of $request["order"][0]['dir'] it always comes up in ascending order. Is there a way to set the ordering to descending order? I have added my JS below.
$sqlRecord .= " ORDER BY ". $columns[$request['order'][0]['column']] ." " . $request["order"][0]['dir'] . " LIMIT " . $request["start"] . " ," . $request["length"]. " ";
$.ajax({
url: "coordinator-activities-table.php",
method: "POST",
success: function(data){
$("#retailer-activities-container").html(data);
table = [
{ "width": "120px", "orderable": false, "targets": 0 },
{ "width": "80px", "targets": 1 },
{ "width": "150px", "targets": 2 },
{ "width": "120px", "targets": 3 },
{ "width": "150px", "targets": 4 },
{ "width": "150px", "targets": 5 },
{ "width": "150px", "targets": 6 },
{ "width": "150px", "targets": 7 },
{ "width": "150px", "targets": 8 },
{ "width": "150px", "targets": 9 },
{ "width": "120px", "targets": 10 },
{ "width": "100px", "targets": 11 },
{ "width": "110px", "targets": 12 },
{ "width": "110px", "targets": 13 },
{ "width": "150px", "targets": 14 },
{ "width": "150px", "targets": 15 },
{ "width": "120px", "targets": 16 },
{ "width": "150px", "orderable": false, "targets": 17 }
];
var table = $('#activities-table').DataTable({
"searching": { "regex": true },
"paging": true,
"autoWidth": false,
"processing": true,
"serverSide": true,
"ajax": {
url: "coordinator-activities-data.php",
type: "POST",
"dataType": "json",
data: {coordinator:coordinator, startdate:startdate, enddate:enddate, regional:regional},
"complete": function(response) {
}
},
"columnDefs": table,
"language": {
"emptyTable": "No data available in table",
"zeroRecords": "No data available in table",
"info": "Showing <b>_START_</b> to <b>_END_ of _TOTAL_</b> entries",
"paginate": {
"first": "First",
"last": "Last",
"next": "Next",
"previous": "Previous"
},
search: "_INPUT_",
searchPlaceholder: "Search..."
},
dom: 'Bfrtip',
buttons: [
'csv', 'excel', 'pdf'
]
});
},
error: function(data){
console.log("error");
}
});
I want to set the default ordering to descending
You can change the Sort data when datatable makes the request to server like this :
var firstsort='DESC';
var table = $('#activities-table').DataTable({
"searching": { "regex": true },
"paging": true,
"autoWidth": false,
"processing": true,
"serverSide": true,
"ajax": {
url: "coordinator-activities-data.php",
type: "POST",
"dataType": "json",
data: function (data) {
var sort = data.order[0].column;
//check condition or remove condition if you want every request with sort DESC
if (firstsort != '') {
data.order[0].dir = "DESC";
firstsort = '';
}
data['coordinator'] = coordinator, data['regional'] = regional,
data['startdate'] = startdate, data['enddate'] = enddate;
return data;
},
"complete": function (response) {
}
},
"columnDefs": table,
"language": {
"emptyTable": "No data available in table",
"zeroRecords": "No data available in table",
"info": "Showing <b>_START_</b> to <b>_END_ of _TOTAL_</b> entries",
"paginate": {
"first": "First",
"last": "Last",
"next": "Next",
"previous": "Previous"
},
search: "_INPUT_",
searchPlaceholder: "Search..."
},
dom: 'Bfrtip',
buttons: [
'csv', 'excel', 'pdf'
]
});
I have used data tables in one of my project, all things are working fine except ordering, we want to use server side sorting, I tried lots of examples but it is not working for me,can anyone please help me to do sorting, I am stuck in this issue, here is my code
episodes_data_table = $('#episodes_table').DataTable({
"processing": true,
"serverSide": true,
"pageLength": 20,
"dom": 'trip<"clear">',
//"dom": 'trilp<"clear">',
"aaSorting": [[0, "desc"]],
"ajax": {
type: "post",
url: "<?php echo base_url(); ?>billing/get_episodes_data",
data: function (d) {
return jQuery.extend({}, d, {
"branch_id": current_branch_id,
"month": $(".month-filter-input").val(),
"year": $(".year-filter-input").val(),
});
}
},
"fnDrawCallback": function (oSettings) {
},
"columnDefs": [
{
"data": "ID",
"render": function (data, type, row) {
return data;
},
"targets": 0,
"visible": false,
"bSortable": false,
},
{
"data": "LastName",
"render": function (data, type, row) {
return data;
},
"targets": 1,
"visible": true,
"bSortable": false,
},
{
"data": "MRN",
"render": function (data, type, row) {
return data;
},
"targets": 2,
"visible": true,
"bSortable": false,
},
{
"data": "SOC",
"render": function (data, type, row) {
return data;
},
"targets": 3,
"visible": true,
"bSortable": false,
},
{
"data": "EpStart",
"render": function (data, type, row) {
return data;
},
"targets": 4,
"visible": true,
"bSortable": false,
},
{
"data": "EpEnd",
"render": function (data, type, row) {
return data;
},
"targets": 5,
"visible": true,
"bSortable": false,
},
{
"data": "PhyFirstName",
"render": function (data, type, row) {
return data;
},
"targets": 6,
"visible": true,
"bSortable": false,
},
{
"data": "SNVisits",
"render": function (data, type, row) {
return data;
},
"targets": 7,
"visible": true,
"bSortable": false,
},
{
"data": "HHAVisits",
"render": function (data, type, row) {
return data;
},
"targets": 8,
"visible": true,
"bSortable": false,
},
{
"data": "MSWVisits",
"render": function (data, type, row) {
return data;
},
"targets": 9,
"visible": true,
"bSortable": false,
},
{
"data": "PTVisits",
"render": function (data, type, row) {
return data;
},
"targets": 10,
"visible": true,
"bSortable": false,
},
{
"data": "OTVisits",
"render": function (data, type, row) {
return data;
},
"targets": 11,
"visible": true,
"bSortable": false,
},
{
"data": "STVisits",
"render": function (data, type, row) {
return data;
},
"targets": 12,
"visible": true,
"bSortable": false,
},
{
"data": "TotVisits",
"render": function (data, type, row) {
return data;
},
"targets": 13,
"visible": true,
"bSortable": false,
},
]
});
Can anyone please look at the code and give me the proper solution ? Any help will be really appreciated.
Here is my AJAX :
$('.customers-datatable').dataTable( {
"order": [[ 0, "asc" ]],
"processing": true,
"serverSide": true,
"ajax": {
url: 'ajax/customers.php?action=list',
type: "POST"
},
"columns": [
null,
null,
null,
null,
null,
{ "orderable": false, "width": "20px" }
]
});
Here is my PHP/MySql :
$req = $pdo->prepare('SELECT * FROM customers');
$req->execute();
$result['draw'] = 1;
$result['recordsTotal'] = $req->rowCount();
$result['recordsFiltered'] = 10;
$result['data'] = array();
while( $row = $req->fetch() ) {
$result['data'][] = array($row['lastname'] . ' ' . $row['firstname'], $row['zipcode'], $row['city'], $row['email'], $row['telephone'], "");
}
$req->closeCursor();
So, instead getting 10 elements, I got the entire list. Here is a preview fo what is rendered :
Any idea on how to limit the table to 10 results ?
Have you checked limit keyword?
SELECT * FROM customers LIMIT 0,10
and in general limit would by combined with ORDER BY some_column DESC to give it more senses (say, by time or by id).
Updated:
to do pagination, just pass in different arguments when switch pages:
SELECT * FROM customers LIMIT 0,10 // 1-10 rows for page 1
SELECT * FROM customers LIMIT 10,10 // 11-20 rows for page 2
SELECT * FROM customers LIMIT 20,10 // 21-30 rows for page 3
.... and so on
Use the pageLength setting in datatables - such as
$('#myTable').dataTable( {
"pageLength": 10
});
This will output 10 rows
Ok, I found the solution to my problem.
Here is my new array of data :
$result['data'][] = array( "name" => $row['lastname'] . ' ' . $row['firstname'],
"zipcode" => $row['zipcode'],
"city" => $row['city'],
"email" => $row['email'],
"telephone" => $row['telephone'],
"action" => "<i class=\"fa fa-close fa-2x text-danger\"></i>"
);
And here is my ajax call (I've set serverSide to false because it broke the pagination) :
$('.customers-datatable').dataTable( {
"order": [[ 0, "asc" ]],
//responsive: true,
"processing": true,
"serverSide": false,
"ajax": {
url: 'ajax/customers.php?action=list',
type: "POST"
},
"columns": [
{ "data": "name" },
{ "data": "zipcode" },
{ "data": "city" },
{ "data": "email" },
{ "data": "telephone" },
{ "data": "action",
"orderable": "false",
"width": "20px"
}
]
});