Send POST parameters to PHP in ajax call of jQuery datatable - php

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

Related

Make datatables load faster with more than 10.000 data

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

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

Datatables server side processing with using Code Igniter

I'm building a forum using Code Igniter framework. I'm trying to implement Datatables server side processing. I know how to use datatables and JQuery for actions such as sorting and searching, but my database table has the potential to grow to thousands and pulling all the rows at once will not make users very happy, so I'm trying to combine both server side (Code Igniter) and client side (AJAX) processing in order to use limits and offsets. So I dug into the web and found an awesome tutorial. This is what I have:
Model: Posts_model.php
<?php
var $table = 'general_posts';
var $column_order = array(null, 'title','body','username','time','category'); //set column field database for datatable orderable
var $column_search = array('title','body','username','time','category'); //set column field database for datatable searchable
var $order = array('id' => 'desc'); // default descending order
private function get_posts_query() {
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item)
{
if($_POST['search']['value'])
{
if($i===0) // first loop
{
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if(isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_gen_posts($category) {
$this->get_posts_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->result();
}
function count_filtered_gen_posts($category) {
$this->get_posts_query();
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->num_rows();
}
public function count_all($category) {
$this->db->where(array('category' => $category, 'display' => 'true'));
$this->db->from($this->table);
return $this->db->count_all_results();
}
} ?>
Controller: Posts.php
<?php
public function __construct() {
parent::__construct();
$this->load->model('posts_model','general_posts');
}
public function posts($category) {
$data['category'] = $category;
$this->load->view('posts', $data);
}
public function posts_ajax($category)
{
$list = $this->general_posts->get_gen_posts($category);
$data = array();
foreach ($list as $post) {
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->general_posts->count_all($category),
"recordsFiltered" => $this->general_posts->count_filtered_gen_posts($category),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
} ?>
View: posts.php
<table id="table" class="table table-no-border" cellspacing="0" width="100%" style="text-align: left">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"paging": true,
"pageLength" : 10,
"lengthChange": true,
"searching": true,
"info": false,
"autoWidth": true,
"ordering": false,
"stateSave": true,
"processing": true,
"serverSide": true,
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo base_url('posts/posts_ajax/'.$category)?>",
"dataType": "json",
"type": "POST",
"data":{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
</script>
So far, everything works as expected, but it does not entirely suit my needs. Look at these lines:
foreach ($list as $post) {
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
}
I'd like the results of each row to display in ONE COLUMN, not in 5 colums. This is because I intend to use Bootstrap panel to display the result of each row, and customise it to suit my needs.
I want something like this for each result:
Post Title: bla bla bla
The body goes here
Posted in: category name
Posted by: name of poster
Time: 9th Sep, 2017 at 10: 30PM
I would like to control how each field is displayed, with stylings and formatings, such as converting the time field into something more human-readable (eg 9th Sep, 2017 at 10: 30PM). The problem is, since the loop is created inside the controller (rather than in view, which I'm used to), I do not know how to go about doing this. I know if I can get the loop between the table body tags ( here ), I can do what I want, but I don't think AJAX will appreciate it if I did (I tried it, 'he' didn't). This is my first dabble into AJAX.
EDIT: I am wondering if there is a way to use the contents of the post_ajax function inside view so that I can put the foreach loop inside the body tag of table.
So I need help. Please help! Sorry it's so long...
Follow the stapes And Get Result
Step 1 : - on view side paste below code
<table id="table_lists" class="table table-bordered table-hover table-striped datatable ">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Day</th>
<th>Holiday</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="javascript">
var t = $('#table_lists').DataTable({
"processing": true,
"serverSide": true,
"ordering": false,
"ajax": {
"url": "<?php echo admin_url('employee/lists'); ?>",
"type": "POST",
},
"columns": [
{ "data": "no" },
{ "data": "date" },
{ "data": "day" },
{ "data": "holiday" },
{ "data": "action"},
],
});
</script>
Step 2: - In Controller create function like these
public function lists(){
$json_data = $this->holiday->get_list_table();
echo json_encode($json_data);
}
Step 3: - Paste Below code in model
public function get_list_table()
{
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$start = $params['start'];
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" AND ";
$where .=" ( ";
$where .=" name LIKE '%".$params['search']['value']."%' ";
$where .=" OR DATE_FORMAT(date, \"%d-%m-%Y\") LIKE '%".$params['search']['value']."%' ";
$where .=" OR DAYNAME(date) LIKE '%".$params['search']['value']."%' ";
$where .=" )";
}
$sql = "SELECT *
FROM {$this->tbl_holiday}
WHERE 1 = 1 {$where}
ORDER BY date ASC";
$sqlTot .= $sql;
$sqlRec .= $sql;
$sqlRec .= " LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = $this->db->query($sqlTot);
$totalRecords = $queryTot->num_rows();
$queryRecords = $this->db->query($sqlRec);
$results = $queryRecords->result();
$i = ($start + 1);
if(!empty($results)) {
foreach ($results as $result) {
$actions = '<a href="javascript:void(0);" onclick="javascript: editHoliday('.$result->id.');" class="btn btn-info btn-sm">
<i class="fa fa-edit"></i>
</a>
<a href="javascript:void(0);" title="Delete" data-toggle="modal" data-target="#confirm-delete" class="btn btn-danger btn-sm" data-href="'.admin_url('holiday/delete/'.$result->id).'">
<i class="fa fa-trash"></i>
</a>';
$data[] = array(
'no' => $i,
'date' => date('d-m-Y', strtotime($result->date)),
'day' => date('l', strtotime($result->date)),
'holiday' => $result->name,
'action' => $actions,
);
$i++;
}
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
return $json_data;
}

Invalid json response in jquery datatable

I have tried jquery datatables for the first time. After referring the manual etc I was able to write the program below, but I am constantly getting an error stating that the json response is invalid.
model file:
public function inbox($data)
{
$con = mysqli_connect("localhost", "root", "","mailman");
$sentFromEmail = $data['sentFromEmail'];
$querySender = "SELECT userId FROM users WHERE userEmail= '$sentFromEmail'";
$resSender = mysqli_query($con, $querySender);
$rowSender = mysqli_fetch_assoc($resSender);
$columnSender = $rowSender["userId"];
$querySender = "SELECT mailId,mailSender,mailSubject,mailContent, mailSendDate FROM mails WHERE mailReceiver = '$columnSender'";
$resSender = mysqli_query($con, $querySender);
$rowSender = mysqli_fetch_assoc($resSender);
$myMail = array();
$test = array();
while($row = mysqli_fetch_array($resSender))
{
$senderId = $row['mailSender'];
$querySenderName = "SELECT userName FROM users WHERE userId= '$senderId'";
$resSenderName = mysqli_query($con, $querySenderName);
$rowSenderName = mysqli_fetch_assoc($resSenderName);
$columnSenderName = $rowSenderName["userName"];
$test[] = $row;
$myMail[] = array(
'mailId' => $row['mailId'],
'mailSender' => $columnSenderName,
'mailSubject' => $row['mailContent'],
'mailContent' => $row['mailSubject'],
'mailSendDate' => $row['mailSendDate']
);
// $myMailData = json_encode($test);
// echo $myMailData;
}
return $test;
}
controller:
public function index()
{
//$userLoginData = $this->session->userdata('user_login');
$data = array(
'sentFromEmail' => $this->session->userdata['user_login']['loginEmail'] ,
);
//load the method of model
$mailBoxData = array();
$mailBoxData['mailBoxData'] = $this->mail_receive->inbox($data);
$jsonData = json_encode($mailBoxData);
echo $jsonData;
$this->load->view('inbox', $mailBoxData);
}
view file:
<script>
$(document).ready(function() {
$('#inbox').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url" : "http://localhost/codeigniter/index.php/Inbox_redirect/index",
"type" : "POST",
"dataSrc": ""
},
"columns" : [
{"data" : "mailId"},
{"data" : "mailSender"},
{"data" : "mailSubject"},
{"data" : "mailContent"},
{"data" : "mailSendDate"} ]
} );
} );
</script>
<table class="table table-hover table-striped" id="inbox" name="inbox">
<thead>
<th>ID</th>
<th>Sent By:</th>
<th>Time</th>
<th>Subject</th>
<th>Message</th>
</thead>
<div class="container">
<tbody>
</tbody>
</div>
</table>
How do I rectify the error?
the json response that getting recorded is
[{"mailId":"13","mailSender":"nikita","mailSubject":"testing","mailContent":"njcndncvjdvnfjvnfvnfjvnjkfnvkfnbkfkbnfdbteb","mailSendDate":"2016-11-16 15:04:20"},{"mailId":"14","mailSender":"nikita","mailSubject":"testing","mailContent":"njcndncvjdvnfjvnfvnfjvnjkfnvkfnbkfkbnfdbteb","mailSendDate":"2016-11-16 15:23:02"},{"mailId":"17","mailSender":"nikita","mailSubject":"wygdyegfhfbvhrvf","mailContent":"ghfgregughuthgujbhjhykhytj","mailSendDate":"2016-11-17 12:55:20"},{"mailId":"21","mailSender":"jyotsna","mailSubject":"hi there","mailContent":"hello, how are you?","mailSendDate":"2016-11-18 14:50:56"}]
Try to add "dataType" inside:
"ajax": {
"url" : "http://localhost/codeigniter/index.php/Inbox_redirect/index",
"type" : "POST",
"dataSrc": ""
}
like this:
"ajax": {
"url" : "http://localhost/codeigniter/index.php/Inbox_redirect/index",
"type" : "POST",
"dataType": "json", // The type of data that you're expecting back from the server.
"dataSrc": ""
}
If this won't work, you can still try to parse the result which you get like this: JSON.parse('your JSON string');. The JSON string which you send from PHP, made with the json_encode() method.

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.

Categories