Make datatables load faster with more than 10.000 data - php

I am new to datatables and I am making a website search data using datatables. But mysql data is more than 10,000. When I try to search data on my web, datatables are very long displaying data. Can anyone help me, how do I get datatables to display tables faster with large data. Thank you
PHP:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "test");
$columns = array('id', 'datetime', 'temperature', 'humidity');
$query = "SELECT id, datetime, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(datetime) BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(id LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= "GROUP BY DATE_FORMAT(datetime, '%d-%M-%Y-%H:%i:%s') ORDER BY 'id'";
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query );
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["datetime"];
$sub_array[] = $row["temperature"];
$sub_array[] = $row["humidity"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM data";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
Javascript:
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#tabel_data').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
filename: 'datatable'
},
],
"paging": false,
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
}
});
dataTable.on('draw.dt', function () {
var info = dataTable.page.info();
dataTable.column(0, { search: 'applied', order: 'applied', page: 'applied', }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + info.start;
dataTable.cell(cell).invalidate('dom');
});
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#tabel_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Date Required");
}
});
});

1) use pagination how to use pagination with PHP and mysql instead of a simple query like below.
"SELECT * FROM data";
2) Dot select * because * will select unnecessary fields also instead define column name for which you want to show data
example:
select name,page,amt from data
your final query will look like
SELECT emp_id, emp_name, emp_salary FROM employee LIMIT $offset, $rec_limit;
check the link above how to use pagination with PHP and mysql

Related

Send POST parameters to PHP in ajax call of jQuery datatable

I want to make a jQuery function in where, getting a value of an input, send it to a PHP file to make a query in mysql and populate a datatable with the information received.
Another problem I have is that the table is initialized when the user is logged in and I don't know if that can obstruct the function I want to do.
This the table:
Table and button
This is where I initialize it:
$.fn.dataTable.ext.errMode = 'none';
var table = $('#m3_sem').DataTable( {
"ajax": "dist/ajax/prueba_m3_sem.php",
"paging": false,
"ordering": false,
"info": false,
"searching": false,
"columns": [
{ "data": "resistencia" },
{ "data": "res1" },
{ "data": "res2" },
{ "data": "res3" },
{ "data": "res4" },
{ "data": "res5" },
{ "data": "res6" },
{ "data": "total" }
],
"order": [[0, 'asc']],
"pagingType": "full_numbers",
"language": {
"sSearch" : "Buscar:",
"lengthMenu": "Mostrando _MENU_ registros por pagina",
"zeroRecords": "No hay pedidos pendientes",
"info": "Mostrando pagina _PAGE_ de _PAGES_",
"infoEmpty": "Sin registros",
"infoFiltered": "(Filtrados de _MAX_ registros totales)",
"paginate" : {
"first" : "Primera pagina",
"previous" : "Anterior",
"next" : "Siguiente",
"last" : "Ultima pagina"
}
}
});
} );
And this is the PHP file "prueba_m3_sem.php", it generates the JSON I use to populate the table:
$sql = "SELECT DISTINCT resistencia ";
$sql.= "FROM registros ORDER BY resistencia";
$query=mysqli_query($conexion, $sql) or die("ajax-grid-data.php: get PO");
$data = array();
while( $row=mysqli_fetch_array($query) ) {
$sumtot = 0;
$nestedData=array();
$nestedData["resistencia"] = $row["resistencia"];
$sqld = "SELECT DISTINCT(fecha_entrega) FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
$queryd=mysqli_query($conexion, $sqld) or die("ajax-grid-data.php: get PO");
$count = 0;
$tot = 0;
while( $rowd=mysqli_fetch_array($queryd) ) {
$count++;
$m3tot = 0;
$sqlm = "SELECT m3 FROM registros WHERE fecha_entrega = '".$rowd["fecha_entrega"]."' AND resistencia =".$row["resistencia"]."";
$querym=mysqli_query($conexion, $sqlm) or die("ajax-grid-data.php: get PO");
while( $rowm=mysqli_fetch_array($querym) ) {
if (empty($rowm['m3'])){
$m3 = 0;
}else{
$m3 = $rowm["m3"];
}
$m3tot = $m3tot + $m3;
}
$tot = $tot + $m3tot;
$nestedData["res".$count] = $m3tot;
$sumtot = $sumtot + $m3tot;
}
$nestedData["total"] = "<b>".$sumtot."</b>";
$data[] = $nestedData;
}
$sqld2 = "SELECT DISTINCT(fecha_entrega) as fecha FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
//echo $sqld;
$queryd2=mysqli_query($conexion, $sqld2) or die("ajax-grid-data.php: get PO");
$totm3 = 0;
$nestedData["resistencia"] = "<b>Total</b>";
$count = 0;
while( $rowd2=mysqli_fetch_array($queryd2) ) {
//echo $rowd["fecha"]."</br>";
$sqltot = "SELECT SUM(m3) AS m3 from registros WHERE fecha_entrega ='".$rowd2["fecha"]."'";
$querytot=mysqli_query($conexion, $sqltot) or die("ajax-grid-data.php: get PO");
while( $rowtot=mysqli_fetch_array($querytot) ){
$count ++;
//echo $rowtot["m3"]."</br>"
$nestedData["res".$count] = "<b>".$rowtot["m3"]."</b>";
$totm3 = $totm3 + $rowtot["m3"];
}
}
$nestedData["total"] = "<b>".$totm3."</b>";
$data[] = $nestedData;
$json_data = array("data" => $data);
echo json_encode($json_data);
I've seen some code examples and the datatable documentation but I just can't find something that fits in the function I need or I just don't understand it very well.
Also, as you can see, English is not my native language. I hope and you can forgive my misspellings.
In advance thanks a lot for your response.
what I understand is that you want to display some results in your table after you submit some search value? if thats the case here is a little example I did using a employees sample db with mysql:
the html:
<div class="container">
<input type="text" name="txtName" id="txtName" value="">
<button type="btn btn-default" name="button" id="btnSearch">Search</button>
</div>
<div class="container" id="tblResult" style="display:none;">
<div class="row">
<div class="col-sm-6">
<table id="example" class="table table-responsive" style="width:100%">
<thead>
<tr>
<th>Cliente</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Device Id.</th>
<th>Client id</th>
<th>Accion</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Cliente</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Device Id.</th>
<th>Client id</th>
<th>Accion</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
I use an input to search employees by a name parameter in this example so if you want to filter by a date it would not be that different.
the javascript:
$(document).ready(function(){
// click event to call the datatable request
$('#btnSearch').on('click', (event) => {
let search = $('#txtName').val();// get the input value
if (search != "") {// validate that the value is not empty
//assing the datatable call to a variable
let example = $('#example').DataTable({
"destroy": true,
"responsive":{//this is usefull if you want to use a full responsive datatable just add the responsive css from dataTables.net
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,//
"ajax": {
"url": 'request.php',
"method": 'POST',
data:{action:"SLC",name:search}//parameter to search and the action to perform
},
"columns": [
{"data": "emp_no"},
{"data": "first_name"},
{"data": "last_name"},
{"data": "gender"},
{"data": "salary"},
{"data": "title"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},//load all dataTables default values in spanish
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});//fin obtener tabla
example.on( 'xhr', function ( e, settings, json ) {// check is the response is not null and show the table
if (json != null) {
$('#tblResult').css("display","");
}
} );
}
});
}); //end ready
As you can see I call the dataTable method until a search is performed also I display the Table if the response is not empty.
the php:
<?php
$host = '127.0.0.1';
$db = 'employees';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$pdo = "";
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// a fucntion that display the employees by our search value
function getEmployeesBySearch($conn,$order,$name) {
$sql = "SELECT e.emp_no,e.first_name,e.last_name,e.gender, gs.salary, gt.title
FROM employees e
inner join (
SELECT s.emp_no,MAX(s.salary) AS salary
FROM salaries s
GROUP by s.emp_no
) as gs on e.emp_no = gs.emp_no
inner join (
SELECT t.emp_no ,t.title ,MAX(t.from_date) as from_date
FROM titles t
WHERE t.to_date = '9999-01-01'
GROUP BY t.emp_no,t.title
) gt on e.emp_no = gt.emp_no
WHERE gt.title = 'Senior Engineer'
AND e.emp_no BETWEEN 10001 and 11819";
//use bind parameters and prepared statement to do the search and prevent sql injection
if ($name != "") {
$sql .= " AND e.first_name like CONCAT( '%', :name, '%')";
}
if ($order == "DESC") {
$sql .= " ORDER BY gs.salary DESC";
}else {
$sql .= " ORDER BY gs.salary ASC";
}
$json= array();
$stmt = $conn->prepare($sql);
if ($name != "") {
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 100);
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$rows = $stmt->fetchAll();
//store the data inside an array
foreach ($rows as $row) {
$tempArray = array(
'emp_no'=>$row["emp_no"],
'first_name'=>$row['first_name'] ,
'last_name'=>$row['last_name'],
'gender'=>$row['gender'],
'salary'=>$row['salary'],
'title'=>$row['title']
);
//json encode the array and send the response back
$json["data"][] = $tempArray;
}
echo json_encode($json);
}
if (isset($_POST["action"])) {
// we set the variables here, since you will add another stuff later I decided a switch to run a specific case with the action the user send
$action = $_POST["action"];
$order = (isset($_POST["order"]) ? $_POST["order"] : "");
$name = (isset($_POST["name"]) ? $_POST["name"] : "");
switch ($action) {
case 'SLC':
getEmployeesBySearch($pdo,$order,$name);
break;
}
}
?>
I use a simple connection here and a function that load the results from my db to send them back as a json rsponse also try to use prepared statements in your querys and bind parameters like the example
Hope it helps =)

Pagination, searching and sorting is not working in jquery datatable in codeigniter using ajax

Currently i am working on eCommerce website in that i have to display all data from database to datatable. Data is coming properly in datatable but searching, sorting and pagination is not working.If any body know solution than please help. Below is my code
Controller.php
Public function transaction_data()
{
$id = $this->session->Vendordetail['id'];
$transactionData = $this->Mdl_vendor_payment->get_order_list($id);
$requestData= $_REQUEST;
$totalData = count($transactionData);
$totalFiltered = count($transactionData);
$return_days = $this->Mdl_common->get_setting('shipping_charge');
foreach($transactionData as $transaction){
$product = $this->Mdl_common->product_id($transaction['prodouct_id']);
$data['order_id'] = $transaction['order_id'];
$data['created'] = $transaction['created'];
if($transaction['status'] == 5){
$data['status'] = '<h5><span class="label label-danger">Cancelled</span></h5>';
}else if($transaction['status'] == 4){
$data['status'] = '<h5><span class="label label-default">Return</span></h5>';
}else if($transaction['status'] == 3){
$data['status'] = '<h5><span class="label label-success">Success</span></h5>';
}else if($transaction['status'] == 2){
$data['status'] = '<h5><span class="label label-primary">Dispatch</span></h5>';
}else if($transaction['status'] == 1){
$data['status'] = '<h5><span class="label label-primary">Ready To Dispatch</span></h5>';
}else{
$data['status'] = '<h5><span class="label label-primary">Approve</span></h5>';
}
$data['price'] = '<i class="fa fa-rupee"></i> '.$transaction['price']*$transaction['qty'];
$data['settlement_price'] = '<i class="fa fa-rupee"></i> '.$transaction['settlement_price']*$transaction['qty'];
$shipping_charge = $return_days['value'] * ($transaction['qty'] * $product['weight']);
$data['shipping_charge'] = '<i class="fa fa-rupee"></i> '.$shipping_charge;
$data['commission_fee'] = ($transaction['price']*$transaction['qty'])-($transaction['settlement_price']-$transaction['qty']);
$data['payable_amount'] = ($transaction['settlement_price']*$transaction['qty'])-$shipping_charge;
$data['order'] = $transaction;
$data['product'] = $product;
$assignment_datas[] = $data;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $assignment_datas
);
echo json_encode($json_data);
die;
}
Below is the code for view file
View.php
$(document).ready(function() {
var dt = $('#datatable_example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url":"<?php echo base_url(); ?>index.php/Vendor_payment/transaction_data",
"type":"POST",
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "order_id" },
{ "data": "created" },
{ "data": "status" },
{ "data": "price" },
{ "data": "settlement_price" },
{ "data": "shipping_charge" }
],
"order": [[0, 'asc']]
} );
// Array to track the ids of the details displayed rows
var detailRows = [];
$('#datatable_example tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dt.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
// Remove from the 'open' array
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
// Add to the 'open' array
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
// On each draw, loop over the `detailRows` array and show any child rows
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
This code is work fine for me...
In view page:
<table id="user_datatable" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 5%;">ID</th>
<th>Client name</th>
<th>Mobile</th>
<th>Email</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#user_datatable').DataTable({
'pageLength': 1,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url': '<?php echo base_url(); ?>user/userList'
},
'columns': [{
data: 'id'
},
{
data: 'name'
},
{
data: 'mobile'
},
{
data: 'email'
},
{
data: 'action'
},
]
});
});
</script>
In Controller page
public function userList() {
$postData = $this->input->post();
$data = $this->Data_model->getUserList($postData);
echo json_encode($data);
}
In Model page
Set the table name in $table variable
// $table = 'clients';
Add column name whatever you add in datatable
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
function getUserList($postData=null) {
$response = array();
$table_name = 'clients';
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$searchQuery = "";
if($searchValue != ''){
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$this->db->select('count(*) as allcount');
$records = $this->db->get($table_name)->row();
$totalRecords = $records->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchValue != '')
$this->db->where($searchQuery);
$records = $this->db->get($table_name)->row();
$totalRecordwithFilter = $records->allcount;
## Fetch records
$this->db->select('*');
if($searchValue != '')
$this->db->where($searchQuery);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$records = $this->db->get($table_name)->result();
$data = array();
foreach($records as $key => $record) {
$data[] = array(
"id"=> ($key + 1),
"name"=>$record->name,
"mobile"=>$record->mobile,
"email"=>$record->email,
"action"=>"<a href='".base_url()."user/update/".$record->id."' type='button' class='btn btn-success'>Update</a><a href='".base_url()."user/delete/".$record->id."' type='button' class='btn btn-danger' style='margin-left: 5px;'>Delete</a>",
);
}
## Response
$response = array(
"draw" => intval($draw),
"recordsTotal" => $totalRecordwithFilter,
"recordsFiltered" => $totalRecords,
"data" => $data
);
return $response;
}

Ajax datatable not properly working in Laravel

I am a stuck with a problem.
I am having an ajax Datatable where I need to load the data via ajax. When I implemented the code Datatable pagination and sorting is not working. No error is displayed in the console. Don't know what to do.
here is my code...........
Controller Function
public function ajaxdata(Request $request)
{
$merchants = \DB::table('merchantsummary')->lists('id');
$queryBuilder = OrderQueueModel::take($request->input('length'))
->skip($request->input('start'))->select('order_queue.qid','order_queue.qorder_no','order_queue.created_at','customer.first_name','customer.last_name','merchant_queue_order.created_at as merchant_order_time')
->join('customer','customer.id','=','order_queue.customerid')
->join('merchant_queue_order','order_queue.qid','=','merchant_queue_order.order_queue_id')
->groupBy('merchant_queue_order.order_queue_id');
$orders = $queryBuilder->get();
$data = array();
$i=1;
foreach($orders as $order):
$merchant = MerchantOrderQueueModel::select('merchantsummary.merchant_name','merchant_queue_order.order_queue_id')
->join('merchantsummary','merchantsummary.id','=','merchant_queue_order.merchant_id')
->WHERE('merchant_queue_order.order_queue_id',$order->qid)
->get();
$merchList = '';
foreach($merchant as $mer):
if($merchList!=''){
$merchList .= ', ';
}
$merchList .= $mer->merchant_name;
endforeach;
$data[] = [ $i,
$order->qorder_no,
ucfirst($order->first_name).ucfirst($order->last_name),
date('d-m-Y H:i A', strtotime($order->created_at)),
date('d-m-Y H:i A', strtotime($order->merchant_order_time)),
$this->dateDifference($order->merchant_order_time,$order->created_at),
$merchList,
'</i> View',
];
$i++;
endforeach;
$totaldata = OrderQueueModel::count();
$totalfiltered = $orders->count();
$json_data = array(
"draw" => intval( $_REQUEST['draw'] ),
"recordsTotal" => intval( $totaldata ),
"recordsFiltered" => intval( $totalfiltered ),
"data" => $data
);
echo json_encode($json_data);
}
TableAjax.js
var orderRecords = function () {
var grid = new Datatable();
grid.init({
src: $("#order_ajax"),
onSuccess: function (grid) {
// execute some code after table records loaded
},
onError: function (grid) {
// execute some code on network or other general error
},
onDataLoad: function(grid) {
// execute some code on ajax data load
},
loadingMessage: 'Loading...',
dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js).
// So when dropdowns used the scrollable div should be removed.
//"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>",
"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.
"lengthMenu": [
[5,10, 20, 50, 100],
[5,10, 20, 50, 100] // change per page values here
],
"pageLength": 5, // default record count per page
"serverSide": true,
"columnDefs":[
{ // set default column settings
'orderable': true, 'targets': [0] },
{ "searchable": true, "targets": [0] },
],
"ajax": {
"url": "order/data", // ajax source
},
"order": [
[1, "asc"]
]// set first column as a default sort by asc
}
});
// handle group actionsubmit button click
grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
e.preventDefault();
var action = $(".table-group-action-input", grid.getTableWrapper());
if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
grid.setAjaxParam("customActionType", "group_action");
grid.setAjaxParam("customActionName", action.val());
grid.setAjaxParam("id", grid.getSelectedRows());
grid.getDataTable().ajax.reload();
grid.clearAjaxParams();
} else if (action.val() == "") {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'Please select an action',
container: grid.getTableWrapper(),
place: 'prepend'
});
} else if (grid.getSelectedRowsCount() === 0) {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'No record selected',
container: grid.getTableWrapper(),
place: 'prepend'
});
}
});
}
Need Help !! Waiting for the response..
The easiest way to apply server side data-table is:
Jquery:
$(document).ready(function() {
$('#data_table').dataTable({
"sServerMethod": "POST",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "get_data.php"
});
});
Php: get_data.php
$start = $_REQUEST['iDisplayStart']; // to handle pagination
$length = $_REQUEST['iDisplayLength']; // to handle pagination
$sSearch = $_REQUEST['sSearch']; // for searching
$col = $_REQUEST['iSortCol_0'];
$arr = array(0 => 'id', 1 => 'first_name', 2 => 'last_name', 3 => 'email');
$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];
$qry = "select id, first_name, last_name, email, position, office from datatables_demo where (first_name LIKE '%".$sSearch."%' or last_name LIKE '%".$sSearch."%' or email LIKE '%".$sSearch."%') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
$qry = "select count(id) as count from datatables_demo";
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$iTotal = $row['count'];
}
$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 => $item['id'],
1 => '<span id="'.$item['id'].'" name="first_name" class="editable">'.$item['first_name'].'</span>',
2 => '<span id="'.$item['id'].'" name="last_name" class="editable">'.$item['last_name'].'</span>',
3 => '<span id="'.$item['id'].'" name="email" class="editable">'.$item['email'].'</span>',
4 => '<span id="'.$item['id'].'" name="position" class="editable">'.$item['position'].'</span>',
5 => '<span id="'.$item['id'].'" name="office" class="editable">'.$item['office'].'</span>'
);
$k++;
}
}
echo json_encode($rec);
Its a little bit tough to understand the code on first time, but it will render full functional server side data-table

Making a hyperlink of each of the rows in data-grid table

I have a script that fills a data-grid table. I want to make a hyperlink of each of the rows that gets displayed.
The hyperlinks should look like <a href"index.php?id=(id of the row)">
How can I do that with my current script.
Here is my script:
<?php
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 => 'id',
1 => 'name',
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" name LIKE '".$params['search']['value']."%'";
}
// getting total number records without any search
$sql = "SELECT id, name FROM `customers`";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch customers data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
Edit 1:
Here I am displaying the data:
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
url :"get.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function(){
$("#employee_grid_processing").css("display","none");
}
}
});
});
</script>
I fixed it by changing the JavaScript.
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bprocessing": true,
"serverSide": true,
"ajax": {
"url": "post1.php",
"type": "POST",
"error": function(){
$("#employee_grid_processing").css("display","none");
}
},
"columnDefs": [ {
"targets": 0,
"render": function ( data, type, full, meta ) {
return 'Link';
}
}
]
});
});
</script>
This code will replace the first column with the text Link and the original result of the first column will be used in the Hyperlink.
I think you have to write a custom mRender to get this link. and add an extra
<th>Link</th> on your table header
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bprocessing": true,
"serverSide": true,
"ajax": {
"url": "get.php",
"type": "POST",
"error": function(){
$("#employee_grid_processing").css("display","none");
}
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "id", "render": function ( data ) {
return 'Link';
}
}
]
});
});
PS please remove my old suggestion from your code.

PHP - Remove last char in while

i know many function to remove char in php. but i'm confused to remove this :
i want remove "," from
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$data= "['$row[keyword]', $row[jumlah]],<br>";
echo $data;}
?>
will give result :
['Smartfren', 1],
['Telkomsel', 1],
i want the output like :
['Smartfren', 1],
['Telkomsel', 1]
How to do that?
big thanks for the response.
UPDATE
based on #orangpill answer say i have printed data like :
['ABC', 6597],
['XYZ', 4479],
['PQR', 2075],
['Others', 450]
i want to make a chart, say the code of js chart have to be like :
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
based on #orangepill now my code :
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data);
?>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Presentase Sentimen Positif'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Nilai',
data: [
<?php while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data); ?>
]
}]
});
});
</script>
It might make sense for you to do this by building an array and imploding it when you want to output
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data);
?>
If you are formatting for this data for consumption by javascript a better approach would be to use json_encode.
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = array($row[keyword], (int)$row[jumlah]);
}
echo "var data = ".json_encode($data).";";
?>
You can also use the substr() function:
$data = "";
while($row = mysql_fetch_array($result)) {
$data .= "['$row[keyword]', $row[jumlah]],<br>";
}
$data = substr($data, 0, -5);
echo $data;
rtrim():
$data = rtrim($data, ',');
or, in your particular example, substr:
$data = substr($data, 0, -5);
to remove the "" as well.

Categories