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']);
Related
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);
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.
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.
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!
the default behaviour of dataTable is good, as long as the number of rows are not 907234. I would like to use Ajax oriented working, so get 10 records per pages, etc. I know I can set AJAX source, but only once, and then paging would be futule. (how would it work, if datatable doesnt know the number of records?) not to mention the searching. So how to start?
The server side approach of Datatable is like so:
$('#dataTable').dataTable({
"sServerMethod": "GET",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "data.php",
"aoColumns": [null, null, null, { "bSortable": false }],
"order": [[ 1, "asc" ]],
"oLanguage": {"sZeroRecords": "No Members found", "sEmptyTable": "No members to display"},
});
The backend i.e data.php should be like so:
<?php
$start = $_GET['iDisplayStart'];
$length = $_GET['iDisplayLength'];
$sSearch = $_GET['sSearch'];
$col = $_GET['iSortCol_0'];
$arr = array(1 => 'oe.org_given_id', 2 => 'usr.name');
$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];
$query = "SELECT usr.id,usr.name,oe.org_given_id FROM users usr JOIN organization_employees oe on usr.id=oe.employee_id WHERE oe.organization_id=".$organization_id." AND (usr.name LIKE '%".$sSearch."%' OR oe.org_given_id LIKE '%".$sSearch."%') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$db=new DB();
$resultSet=$db->SelectRead($query);
while($row = mysqli_fetch_assoc($resultSet))
{
$data[] = $row;
}
$counterQuery = "SELECT COUNT(usr.id) as total FROM users usr JOIN organization_employees oe on usr.id=oe.employee_id WHERE oe.organization_id=".$organization_id.";";
$countSet = $db->SelectRead($counterQuery);
$iTotal=0;
while($counterRow = mysqli_fetch_assoc($countSet))
{
$iTotal = $counterRow['total'];
}
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data))
{
foreach ($data as $item)
{
$rec['aaData'][$k] = array(
0 => $k,
1 => $item['org_given_id'],
2 => $item['name'],
3 => "Delete"
);
$k++;
}
}
header("Content-type:application/json");
echo json_encode($rec);
?>
The parameters like:
iDisplayStart and iDisplayLength etc are default given by Datatables.
Some online working examples are:
https://coderexample.com/datatable-demo-server-side-in-phpmysql-and-ajax/
http://phpflow.com/php/datatables-example-server-side-processing-with-php/
http://phpflow.com/demo/datatable/
A github repository of my code is below with some additional features offcourse:
https://github.com/shaktiphartiyal/DataTable-Editor-Free