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;
}
Related
My target is to how can I fetch my data looking like they're matched (They will be matched based on their points? (See the 2nd table)
Here in this first table, we can see that these are all the players who are registered.
id
player
points
1
miguel
1
2
law
1
3
paul
2
4
zafina
2
5
ogre
3
6
noctis
3
7
baek
4
8
hwoarang
4
After creating some query, they'll be matched if they have the same points. (See the table below).
id
player
points
player
points
1
miguel
1
law
1
2
paul
2
zafina
2
3
ogre
3
noctis
3
4
baek
4
hwoarang
4
This is how i fetch my data from DB
html:
<table id="players" class="table table-bordered table-hover" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>player</th>
<th>points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Ajax:
$(document).ready(function() {
//datatables
table = $('#players').DataTable({
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],
"processing": false,
"serverSide": true, mode.
"order": [],
"ajax": {
"url": "<?php echo site_url('controller/function')?>",
"type": "POST",
async:true,
dataType: "json",
"data": function(data){
},
},
});
});
controller:
public function function()
{
$list = $this->model->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->id;
$row[] = $person->player;
$row[] = $person->points;
//add html for action
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->model->count_all(),
"recordsFiltered" => $this->model->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
model
var $table = 'players';
var $column_order = array(null,'id','player','points');
var $order = array('id' => 'desc');
var $column_search = array('id','player','points');
private function _get_datatables_query()
{
$this->db->from($this->table);
// $this->input->post('start'); // YYYY-mm-dd
// $this->input->post('end'); // YYYY-mm-dd
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$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(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$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_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
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 =)
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;
}
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
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.