PHP doesn't receive ajax post data - javascript

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);

Related

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.

Datatables Throwing Invalid JSON Response

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.

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 )
);
}
?>

UTF8 characters not displaying properly with datatables and yadcf

I have a mysql database that is in UTF8, I've properly output the letters before but cannot make my php do so with datatables using the ajax process. I have tried various methods to get the UTF8 to show, including, changing headers, using mysql functions, and changing the json encode function, but I cannot make it work. Please help me show UTF8 properly instead of ?s.
I have: temps.php
My server side processing script:
<?php
header("Content-Type: text/json; charset=utf-8");
require( 'ssp.class.php' );
$table = 'articles';
$primaryKey = 'id';
$columns = array(
array( 'db' => 'title', 'dt' => 0 ),
array( 'db' => 'description', 'dt' => 1 ));
$sql_details = array(
'user' => 'root', 'pass' => 'pass', 'db' => 'test', 'host' => 'localhost'
);
$db = SSP::db($sql_details);
.....
if($clause !== ""){
$whereAll[] = $clause;
$_GET['columns'][$i]['search']['value'] = "";
}}
echo json_encode(
SSP::complex( $_GET, $db, $table, $primaryKey, $columns, null,
(!empty($whereAll) ? implode(" AND ", $whereAll) : "")
));
I have: temp.html: My Javascript function (based on datatables and yadcf)
$(document).ready(function(){
$("#example").dataTable({
"responsive": true,
"processing": true,
"serverSide": true,
"ajax": "scripts/temps.php",
"columns": [
// ID
null,
// Distributor
null
// Director
]
}).yadcf([
// ID
{
column_number: 0 ,
filter_type: "text",
filter_reset_button_text: false
},
// Abstract
{
column_number: 1,
filter_type: "text",
filter_delay: 500,
filter_reset_button_text: false
},
]);
});
And I have temp.html where the data is outputted: (redacted because a lot of the code is irrelevant to the question)
<!DOCTYPE html>
<div>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="Description" CONTENT=""/>
..........
<table id="example" class="table table-striped table-bordered table-condensed" cellspacing="0" width="100%">
<thead>
<tr>
<th><div>One</div></th>
<th><div>Two</div></th>
</tr>
</thead>
</table>
Sorry for such a long question; but what else can I change to make UTF8 properly show on the html page? I've tried all the combinations of variables and functions I can think of; but can't make it work. Perhaps there is a js function that could be applied somewhere? Thank you for the help.
Edit: SQL structure for reference:
CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL,
`title` varchar(300) CHARACTER SET utf8 DEFAULT NULL,
`description` text CHARACTER SET utf8
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
-- Dumping data for table `articles`
INSERT INTO `articles` (`id`, `title`, `description`) VALUES
(1, 'శ్రీనివాస్scddadas తామాడా', '新概念英语第asv'),
(2, 'asda', 'asdవా'),
3, 'sdfsadfsdf英语', 'sadf英');
You need to force utf8 in the PDO connection :
$db = SSP::db($sql_details);
$db->exec("set names utf8");
alternatively, try pass it as a param :
$sql_details = array(
'user' => 'root',
'pass' => 'ryan',
'db' => 'edata',
'host' => 'localhost',
'charset' => 'utf8'
);
But this does not work with all PHP versions.
PS: Why do you set the table fields to be of type utf8, but the table character set to be latin1?
If you have added all the columns as "UTF-8" and still the problem persists then try this
Add these lines on the server side file
mysql_query("SET character_set_client=utf8",$gaSql['link']);
mysql_query("SET character_set_connection=utf8",$gaSql['link']);
mysql_query("SET character_set_results=utf8",$gaSql['link']);

Categories