Datatables returns all rows instead 10 - php

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"
}
]
});

Related

How to fix "cannot reinitialize datatable"

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

Server-side processing default order

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 am using Data Tables ajax , but pagination , search bar, length menu not working

I am using Data Table AJAX, get data from JSON, data table pagination, search bar not working. This is my code.Get data from (progress_play_transactions.php) file in JSON
progress_play_transactions.php (code)
$data[] = array(
"OriginalTransactionID" => "$OriginalTransactionID",
"PlayerID" => "$PlayerID",
"CasinoName" => "$CasinoName",
"TransactionDate" => "$TransactionDate",
"TransactionType" => "$TransactionType",
"Currency" => "$Currency",
"CurrencySymbol" => "$CurrencySymbol",
"TransactionOriginalAmount" => "$TransactionOriginalAmount",
"TransactionDetails" => "$TransactionDetails",
"Status" => "$Status"
);}
echo json_encode(array("result"=>$data,
"recordsTotal" => intval( $totalrecords ),
"recordsFiltered" => intval($totalrecords)
)
);
progress_play.php (code)
$(document).ready(function () {
$('#examples').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax": {
"url": "progress_play_transactions.php",
"type": "json",
"dataSrc": "result"
},
"columns": [
{ "data": "OriginalTransactionID" },
{ "data": "PlayerID" },
{ "data": "CasinoName" },
{ "data": "TransactionDate" },
{ "data": "TransactionType" },
{ "data": "Currency" },
{ "data": "CurrencySymbol" },
{ "data": "TransactionOriginalAmount" },
{ "data": "TransactionDetails" },
{ "data": "Status" }
],
});
});

render datatables columns fetched via ajax

I'm using datatables via ajax and display the table like this
var table = $('#data').DataTable( {
"ajax": "initTable.php",
"columns": [
{ "data": "orderid" },
{ "data": "first_name"},
{ "data": "last_name"},
{ "data": "unix" },
{ "data": "final_total" }
]
} );
I've tried
{ "data": "first_name" + "data": "last_name"},
But I get an error and table is not displayed. So how can I change the render to display first name next to last_name in the same cell not in the next cell
[UPDATE]
Tried
"ajax": "initTable.php",
"columns": [
{ "data": "orderid" },
{ "data": "first_name"},
{"data": "last_name"},
{ "data": "unix" },
{ "data": "final_total" }
],
"columnDefs": [
{
"render": function ( data, type, row ) {
return data + row[2];
},
"targets": 1
},
{ "visible": false, "targets": [ 2 ] }
]
(Note: I have to define column rows because I get many columns (about 20) and want to display just 4 or 5)
But I get the first name followed by 'undefined' something like "Andy undefined"
Use the code below:
{
"render": function ( data, type, row ){
return row["first_name"] + " " + row["last_name"];
},
"targets": 1
},
Also there is no need to include last_name column if you're hiding it.

Datatable server-side script

I've found this piece of code which looks to work for some people,
$dataArr['aaData'] = Array();
while($row = $res->fetch_assoc()){
$r = Array();
foreach($row as $key=>$value){
$r[] = "$key $value";
}
$dataArr['aaData'][] = $r;}
header('Content-Type: application/json');
echo json_encode($dataArr);
/* The output will be of the form,
{"aaData": [ [
[
"colname data"
...
],
] */
but I get an error " Table id =datos Invalid json response.
My Datatable columns do not have the same name as my db columns, and I'm not sure how to handle that.
Here is my js :
$(document).ready(function() {
function getCpAndVille(data, type, dataToSet) {
return data.cp + " " + data.ville;
}
$('#datos').dataTable({
"order": [[ 3, "desc" ]],
"bProcessing": true,
"sAjaxSource": 'ajx/datatable_process_search.php',
"aoColumnDefs": [
{ "sName": "Réf.", "aTargets": [ 0 ] },
{ "sName": "Poste", "aTargets": [ 1 ] },
{ "sName": "Type de contrat", "aTargets": [ 2 ] },
{ "sName": "Date de publication", "aTargets": [ 3 ]},
{ "sName": "Lieu", "aTargets": [ 4 ], "mData": getCpAndVille },
{ "sName": "Descriptif", "aTargets": [ 5 ] }
],
Can someone tell me the right php code I should use, please, because it's quite hard to find it, and I don't understand the example given in http://www.datatables.net/examples/data_sources/server_side.html
Thanks in advance.
Console Network --> {"aaData":[["job_id 9261","job_intitule Assistant Achats","job_contrat Int\u00e9rim","job_date_insertion 2015-02-20","cp 06110","job_ville 19"], and so on...
For those who are looking for a serverside script including JOIN table
https://www.daniweb.com/web-development/php/threads/467455/convert-datatables-to-server-side-processing

Categories