Datatables Throwing Invalid JSON Response - javascript

I am facing issues with the Datatables plugin while fetching data using SSP. I had used the Custom SSP library, but that is returning an error of Invalid JSON response. Anybody here who has implemented the custom SSP library? I will have to use JOINS, WHERE, GROUP BY, etc. I am also open to suggestions on how to implement a Live Filtering function in tables using PHP as shown in the example table here. So if you guys have any idea on how to implement this without using Datatables, that would also work fine.
DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Initialisation
< script >
$(document).ready(function() {
$('#example').DataTable({
colReorder: true,
"scrollX": true,
"processing": true,
"serverSide": true,
"ajax": "rep_down_data.php"
});
}); <
/script>
The one with the JOIN query. The Custom SSP Library has been used here.
<?php
$table = 't_user';
$primaryKey = 'id';
$columns = array(
array( 'db' => 'is_phone_verified', 'dt' => 0 ),
array( 'db' => 'email', 'dt' => 1 ),
array( 'db' => 'mobile_number', 'dt' => 2 ),
array( 'db' => 'first_name', 'dt' => 3 ),
array( 'db' => 'last_name', 'dt' => 4 ),
array( 'db' => 'rep_code', 'dt' => 5 ),
);
require('config.php');
$sql_details = array(
'user' => $db_username,
'pass' => $db_password,
'db' => $db_name,
'host' => $db_host
);
require('ssp.customized.class.php' );
$joinQuery = "FROM `t_user` AS `u` JOIN `t_user_course` AS `ud` ON (`ud`.`user_id` = `u`.`id`)";
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $joinQuery )
);
This is running fine and has the Datatables SSP file (rep_down_data.php)
<?php
$table = 't_user';
$primaryKey = 'id';
$columns = array(
array( 'db' => 'created_at', 'dt' => 0 ),
array( 'db' => 'email', 'dt' => 1 ),
array( 'db' => 'mobile_number', 'dt' => 2 ),
array( 'db' => 'first_name', 'dt' => 3 ),
array( 'db' => 'last_name', 'dt' => 4 ),
);
require('config.php');
$sql_details = array(
'user' => $db_username,
'pass' => $db_password,
'db' => $db_name,
'host' => $db_host
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
The HTML code for the table
<section id="column-filtering">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Rep Downloads</h4>
<a class="heading-elements-toggle"><i class="la la-ellipsis-v font-medium-3"></i></a>
<div class="heading-elements">
<ul class="list-inline mb-0">
<li><a data-action="collapse"><i class="ft-minus"></i></a></li>
<li><a data-action="reload"><i class="ft-rotate-cw"></i></a></li>
<li><a data-action="expand"><i class="ft-maximize"></i></a></li>
<li><a data-action="close"><i class="ft-x"></i></a></li>
</ul>
</div>
</div>
<div class="card-content collapse show">
<div class="card-body card-dashboard">
<table id="example" class="display nowrap table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th>Enr. Date</th>
<th>Email</th>
<th>Mobile Number</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Enr. Date</th>
<th>Email</th>
<th>Mobile Number</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</section>

First, off, you don't need to specify column headers within your HTML. You may set those using columns / columnDefs options with title property. That way, you will not see the table with default styling before DataTable gets initialized. Your table markup may simply look like: <table id="example" ...></table>.
But that, of course, is not the root cause of your problem.
What looks suspicious to me is your SQL. It looks like you're referring twice to your t_user table: first time, by setting $table variable, second, with this part of your $joinQuery - FROM
t_user. So, if you have a chance to throw back the output of the query, say, with var_dump() in the appropriate place of your code, or echo the query itself to check its validity, I guess, that would've give you a hint.
Another thing you must be sure of, is that your SQL output contains the array of arrays or array of objects that correspond to your rows and either of those are encompassed within data / aaData of your output JSON. Otherwise, you may need to specify JSON property that holds your array within ajax.dataSrc option, or set it to empty string if your JSON is an array itself.

Related

PHP doesn't receive ajax post data

I have been struggling with it for a week...I want to use Ajax in datatables to pass some parameters to my PHP file for server side searching. But it seems my PHP file got nothing. But the datatable works just fine and the table can return from sever side processing and display on the html page correctly. However, var_dump( $_POST['species']) returns null.
$(document).ready(function() {
console.log(species);
$("#table").DataTable({
"destroy": true,
"serverSide": true,
"processing": true,
"paging": false,
"searching": false,
columns: [{
data: "d"
},
{
data: "c"
},
{
data: "p"
}
],
ajax: {
type: "POST",
data: {
"species": s
},
url: "./php/search_test.php"
}
});
});
<div class="container text-center" id="tablecontainer" name="tablecontainer">
<table id="table" class="display nowrap row-border strip p-2" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th>
<center>d</center>
</th>
<th>
<center>C</center>
</th>
<th>
<center>P</center>
</th>
</tr>
</thead>
</table>
</div>
'''php
ini_set ('memory_limit', '2048M');
$sql_details = array(
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'db' => 'xxxxx'
);
// DB table to use
$table = 'h';
//if I try this here: $s=$_POST["s"]; echo $s;It
//returns: Warning: Undefined array key "s".
// Table's primary key
$primaryKey = 'd';
// column
$columns = array(
array( 'db' => 'd', 'dt' => 'd' ),
array( 'db' => 'c', 'dt' => 'c' ),
array( 'db' => 'p', 'dt' => 'p' ),
);
// Include SQL query processing class
require( 'ssp.class.php' );
echo json_encode(
SSP::complex( $_POST, $sql_details, $table, $primaryKey,$columns)
);
Could someone help me with it? Thanks.
Try this. Replace $_POST to $array
$array = json_decode(file_get_contents('php://input'), true);
print_r($array);

Ajax server side proc ends in Invalid JSON response

I started with PHP/Ajax/javascript 2 days ago. Currently I try out server side processing on datatables..
I've two files on my webserver. One to display and one to process files.
Here the code:
<!DOCTYPE html>
<html>
<head>
<title>Person Information</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/server_processing.php"
} );
} );
</script>
</head>
<table id="example" class="display" style="width:100%">
<thead><tr>
<th title="Field #1">playerid</th>
<th title="Field #2">playername</th>
<th title="Field #3">age</th>
<th title="Field #4">nation</th>
<th title="Field #5">teamid</th>
<th title="Field #6">team</th>
<th title="Field #7">overall</th>
<th title="Field #8">potential</th>
</tr></thead>
</table>
<?php
$table = 'example';
$primaryKey = 'playerid';
$columns = array(
array( 'db' => 'playerid', 'dt' => 0 ),
array( 'db' => 'playername', 'dt' => 1 ),
array( 'db' => 'age', 'dt' => 2 ),
array( 'db' => 'nation', 'dt' => 3 ),
array( 'db' => 'teamid', 'dt' => 4 ),
array( 'db' => 'team', 'dt' => 5 ),
array( 'db' => 'overall', 'dt' => 6 ),
array( 'db' => 'potential', 'dt' => 7 )
);
$sql_details = array(
'user' => 'myusername',
'pass' => 'mypassword',
'db' => 'mydatabasename',
'host' => 'localhost'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
I get this message: DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
I tried to debug it and found out that this adress get called:
http://webserver.com/server_processing.php?draw=1&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=4&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=5&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=6&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B7%5D%5Bdata%5D=7&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1581016871964
but there is no answer. Any ideas how to fix?

How to use $_GET inside server side processing script of Datatables?

I'm using this example's code https://datatables.net/examples/server_side/simple.html
I want to use $_GET variable in the server_processing.php file so that I can specify the value and doing this from the url. For example table.php?table-id=table1
index.html
Table 1
Table 2
Table 3
table.php
<?php
// Get
$var = $_GET['table-id'];
?>
<table id="example" style="width:100%">
<thead>
<tr>
<th>Payslip ID</th>
<th>Employee ID</th>
<th>Employee Name</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "scripts/server_processing.php"
} );
} );
</script>
scripts/server_processing.php
<?php
// DB table to use
$table = '$var';
// Table's primary key
$primaryKey = 'id';
// indexes
$columns = array(
array( 'db' => 'first_name', 'dt' => 0 ),
array( 'db' => 'last_name', 'dt' => 1 ),
array( 'db' => 'position', 'dt' => 2 )
);
// SQL server connection information
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'sampledb',
'host' => 'localhost'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
variable table-id is undefined. Is there a way to do this? The link part is important so I cannot remove that from the code.
You need to pass the value of $_GET['table-id'] through to the AJAX call by using the ajax.data feature.
The ajax.data option provides the ability to add additional data to the request, or to modify the data object being submitted if required.
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": {
"table_id": <?= $_GET['table_id'] ?>
}
}
} );
Then $_GET['table_id'] should be available within scripts/server_processing.php.

pagination in server side datatable not working (without changing the URL)

i have a datatable for which my jquery is as follows,
$('#example').DataTable({
"lengthMenu": [[10,15,20,25,-1], [10,15,20,25,'All']],
"processing": true,
"serverSide": true,
ajax: {
url: 'url2',
dataSrc: 'data'
},
columns: [
{ data: 'column1' },
{ data: 'column2' },
{ data: 'column3' },
{ data: 'column4' },
{ data: 'column5' },
{ data: 'column6' }
]
});
this is working properly. The only issue is although its showing pagination links, they are not clickable and all the rows are displayed in first page itself.
for eg. if there are 100 rows, the links are getting generated 1-10 but all the 100 records are showing on the first page itself.
I've referred ,
https://datatables.net/examples/data_sources/server_side
what am i doing wrong here?
Thank you for your suggestions
Server side code -
$total_records = $this->model2->getTotal();
$query['results'] = $this->model1->get_Data();
$data = array('data' => $query['results'],
"draw" => (isset($_REQUEST["draw"]) ? $_REQUEST["draw"] : 0),
"recordsTotal" => $total_records,
"recordsFiltered" => $total_records
);
echo json_encode($data);
I think i know what am i doing wrong,
when i print $_GET in my php code it comes out to be empty. But it is supposed to have the limit and offset value.
How to i send limit offset in $_GET?
You need to know how many records go on a page, and how many records there are.
Your SQL will end in OFFSET 30 LIMIT 10 (for example).
First get total Records. Page will come through your URL and default to page 1 if not set.
The offset is calculated like this (example, page 3):
$totalPages = ceil($totalRecords / $numPerPage); // round up the way.
$offset = ($page * $numPerPage) - $numPerPage; // (3 * 10 = 30) - 10 = offset 20
Your SQL will therefore grab records with OFFSET 20 LIMIT 10
This is what your server.php should looks like. Think you are missing some lines of code:
<?php
$table = 'employees';
$primaryKey = 'id'; // Table's primary key
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'first_name', 'dt' => 1 ),
array( 'db' => 'last_name', 'dt' => 2 ),
array( 'db' => 'position', 'dt' => 3 ),
array( 'db' => 'date', 'dt' => 4 ),
array( 'db' => 'updated', 'dt' => 5 ),
);
$sql_details = array(
'user' => 'username',
'pass' => 'password',
'db' => 'database',
'host' => 'localhost'
);
require( 'ssp.class.php' );
echo json_encode(
SSP::simple( $_POST, $sql_details, $table, $primaryKey, $columns )
);
?>
End result: https://databasetable-net.000webhostapp.com/
This should get you in the right direction. Think the ssp.class.php file might need added too, unsure if you have it (you can find it on github). Hope this helps!

dataTable, add row button when using serverside processing

I use server side processing files from the download as starting point with the ssp.class.php file. All works fine, but not the button. In the last column, I want to add some buttons. A lot to be found about this, but not working for me because I defined column data in php and not js. I can't put a function inside the column array like in the js examples.
I have the following code running:
<script type="text/javascript">
$(document).ready(function() {
pageSetUp();
var table = $('#dt_basic').dataTable({
"processing": true,
"serverSide": true,
"ajax": "index.php?loc=client/clients"
});
});
</script>
PHP
<?php
public function clients() {
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'address', 'dt' => 2 ),
array( 'db' => 'telephone', 'dt' => 3 ),
);
$table = 'clients';
$primaryKey = 'id';
$sql_details = array(
'user' => #####,
'pass' => #####,
'db' => #####,
'host' => #####
);
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
}
?>

Categories