after initialize data-table in my page its working fine, but i need to display server response data dynamically in data-table. I can receive data in console.log(data)
$(document).ready(function () {
$.ajax({
url: 'xxxxxx/xxxxxxx',
method: 'POST',
success: function (data) {
$('#datatable').dataTable({
data: data,
serverside:true,
columns: [
{ 'data': 'UserId' },
{ 'data': 'UserDepartment' },
{ 'data': 'UserCourse' },
{ 'data': 'UserName' },
{ 'data': 'UserBirthDate' },
{ 'data': 'UserEmail' },
{ 'data': 'UserContact' }
]
});
}
});
});
Try This:
<?php
$sql = "SELECT FROM user";
$sql_result = $conn->query($sql);
$response = array('data' => $sql_result );
echo json_encode($response);
?>
$(document).ready(function() {
$.ajax({
url: 'xxxxxx/xxxxxxx',
method: 'POST',
dataType: 'json',
success: function(data) {
$('#datatable').dataTable({
data: data,
serverside: true,
columns: [{
'data': 'UserId'
}, {
'data': 'UserDepartment'
}, {
'data': 'UserCourse'
}, {
'data': 'UserName'
}, {
'data': 'UserBirthDate'
}, {
'data': 'UserEmail'
}, {
'data': 'UserContact'
}]
});
}
});
});
I think you have things out of order you could try this:
$(document).ready(function ()
{
// Setup - add a text input to each footer cell
$('#DataTable tfoot th').each(function ()
{
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
var table = $('#DataTable').DataTable({
"select": true,
"processing": true,
"serverSide": true,
"ajax": {
"url": "./ServerSide.php",
"type": "POST"
}
});
});
I'm pretty sure you don't even have to list the column names, they'll be picked up in your file passed to the url.
HTML CODE
<table class="table table-bordered" id="datatables">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
jQuery(document).ready(function(){
$('#datatables').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
"url": "fetch.php",
"dataType": "json",
"type": "POST"
},
"columns": [
{ "data": "id"},
{ "data": "name"},
{ "data": "email"},
{ "data": "mobile"},
{ "data": "manage"}
],
"columnDefs": [ {
"targets": [0,4],
"orderable": false
} ],
"order": [[ 1, "ASC"]],
});
$(document).ready(function() {
$('#dataTables').DataTable();
} );
});
</script>
PHP CODE
$link = mysqli_connect("localhost","root","","dbName")
$req = mysqli_query($link,"SELECT * FROM register where delete_status = 0");
$s = (isset($_POST['search']['value'])) ? $_POST['search']['value'] : '';
if(!empty($s))
{
$req = mysqli_query($link,"SELECT * FROM register WHERE name LIKE '%$s%' ");
}
$totalData = mysqli_num_rows($req);
$totalFiltered = mysqli_num_fields($req);
$data = array();
if(!empty($req))
{
foreach ($req as $key=>$value)
{
$edit = "";
$delete = "";
$nestedData['id'] = $key+1;
$nestedData['name'] = $value['name'];
$nestedData['email'] = $value['email'];
$nestedData['mobile'] = $value['mobile'];
$nestedData['manage'] = "<a href='$edit' class='btn btn-warning btn-xs'><i class='fa fa-pencil'></i> Edit</a> <a onclick='return delet()' href='$delete' class='btn btn-danger btn-xs confirm-delete' ><i class='fa fa-trash'></i> Delete</a>";
$data[] = $nestedData;
}
}
$json_data = array(
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered),
"data" => $data
);
echo json_encode($json_data);
include jquery file
jquery.min.js
bootstrap.min.js
jquery.dataTables.min.js
dataTables.buttons.min.js
dataTables.bootstrap.min.js
Related
I tried to make dropdown search.. how do I make a datatable with ajax response in the form of html if I use codeigniter?
I have tried the console to display the html in response ajax and it works but the response data cannot run on the datatable..
this is my ajax and php code
$(document).ready(function(){
$('#example').DataTable();
$("#periode1").on('change', function(){
var value = $(this).val();
$.ajax({
url: '<?= base_url('Kriteria/getPost') ?>',
type: 'POST',
data: 'request='+value,
success:function(data)
{
console.log(data);
$("#tampil_kriteria").html(data);
$('#example').DataTable();
}
});
});
});
.
public function getPost()
{
$data['title'] = 'Manajemen Data';
$data['title2'] = 'Daftar Kriteria';
$data['user'] = $this->Kriteria_model->getUserById();
$data['periode'] = $this->Kriteria_model->getAllPeriode();
$this->load->view('templates/header', $data);
$this->load->view('templates/menu', $data);
$id = $this->input->post('request');
if($id){
$data['kriteria2'] = $this->Kriteria_model->getAllKriteria($id);
$this->load->view('kriteria/tampil_kriteria', $data);
} else {
$id = $this->Kriteria_model->getId();
$data['kriteria'] = $this->Kriteria_model->getAllKriteria($id);
$this->load->view('kriteria/index', $data);
}
$this->load->view('templates/footer');
}
A possible solution could be:
encode the result of your php script in JSON format as:
{
"data": [
{
"title": "Manajemen Data",
"title2": "Satou",
"user": "Accountant",
"periode": "Tokyo",
......
},
{
"title" : "myTitle2",
..........
}
]
}
Change your Jquery function as:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "myPhpScript.php",
"type": "POST"
},
"columns": [
{ "data": "title" },
{ "data": "title2" },
{ "data": "user" },
{ "data": "periode" },
..........
]
} );
where title, title2, user, periode, ... are the name of the columns in HTML code
Im fetching my data in my server side and I put checkbox.
I need some clarification, do I need to put checkbox here or it will be automatically added?
Controller
$result[] = array(
'#' => '<span style="font-size: 12px; color: gray">'.$counter++.'</span>',
'number' => '<p>'.$value->number.'</p>',
'vendor' => '<p>'.$vendor->name .'</p>',
'document_reference' => '<p>'.$value->document_reference.'</p>',
'date_needed' => '<p>'.$value->date_needed.'</p>',
'requesting_department' => '<p>'.$department->name.'</p>',
'amount' => '<p align="right">'.number_format($value->total_amount,2).'</p>',
'status' => '<p>'.$status.'</p>',
'approval_status' => '<p id="'.$value->id.'">'.$approval.'</p>',
'created_by' => '<p id="created_at'.$value->id.'">'.$user->name.'</p>',
'action' => '<i class="fa fa-eye"></i>',
'checkbox' => '<input type="checkbox" name="checkbox[]" value="'.$value->id.'">'
In my view page I used route to call this method. In here I have now my data.
My View
var table3 = $('#get-rfp-for-approval-table').DataTable({
'processing': true,
'serverSide': true,
ajax: {
url: '/requests/request-for-payment/getRFPforApproval',
dataSrc: ''
},
columns: [
{ data: '#' },
{ data: 'number' },
{ data: 'vendor' },
{ data: 'document_reference' },
{ data: 'date_needed' },
{ data: 'requesting_department' },
{ data: 'amount' },
{ data: 'status' },
{ data: 'created_by' },
{ data: 'approval_status' },
{ data: 'action' },
{ data: 'checkbox' },
],
columnDefs: [
{
targets: 11,
checkboxes: {
selectRow: true
}
}
],
select: {
style: 'multi'
},
order: [[1,'desc']]
});
Example I have 15 data, I checked data 5 and data 14. then I submit the form.
My form
if ( $('#approved-selected-form').length > 0 ) {
$('#approved-selected-form').submit(function(e){
var form = this;
var rows_selected = table3.column(0).checkboxes.selected();
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'checkbox[]')
.val(rowId)
);
});
var formData = $(this).serialize();
swal({
title: "Are you sure?",
text: "Transaction will be approved.",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willSave) => {
if (willSave) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
url: '/requests/request-for-payment/approvedTransaction',
type: "POST",
data: formData,
beforeSend: function() {
var span = document.createElement("span");
span.innerHTML = '<span class="loading-animation">LOADING...</span>';
swal({
content: span,
icon: "warning",
buttons: false,
closeOnClickOutside: false
});
$('.request-for-payment-finish').attr('disabled', 'disabled');
},
success: function(response) {
if (response != '') {
$('#get-request-for-payment-table').DataTable().destroy();
getRequestForPaymentTable();
$('#add-request-for-payment-form').trigger("reset");
swal("Transaction has been saved!", {
icon: "success",
});
setTimeout(
function()
{
window.location.href = "/requests/request-for-payment?id="+response+"#view-request-for-payment-modal";
}, 1500);
}
},
complete: function() {
$('.request-for-payment-finish').removeAttr('disabled');
}
});
} else {
swal("Save Aborted");
}
});
e.preventDefault();
return false;
})
}
NOTE: I tried to dd it in my controller it gives me this
array:1 [
"get-rfp-for-approval-table_length" => "10"
]
I also noticed that in my th, I dont have checkbox(when I clicked this, everything will be checked). Im using this as a guide. https://jsfiddle.net/snqw56dw/3182/.
Question: How can I get those values in my controller?
You should be returning ID in your controller.
$result[] = array(
// ... skipped ...
'checkbox' => $value->id
);
Also since checkbox in column with index 11, you should be using that index when retrieving the data.
var rows_selected = table3.column(11).checkboxes.selected();
On the side note, I see that you're using server-side processing mode ('serverSide': true). Make sure your controller returns proper response.
I have 'post' table in my database. In post table, I have 'LanguageID' column.
When I store/save data, It will make two records, first record with language id = 1 and the second record with language id = 2.
Now, I want to show all 'post' data separately.
Controller
public function index(Request $request)
{
$languages = Language::where('IsActive', 1)->get();
if($request->ajax()) {
foreach ($languages as $lang) {
$post = Post::where('LanguageID', $lang->id)->get();
}
return Datatables::of($post)
->addColumn('action', function($post){
return '<a id="edit" class="btn btn-info"
href="post/' . $post->id . '/edit">
<i class="glyphicon glyphicon-edit icon-white"></i>
Edit
</a>
<button type="button" class="btn btn-danger"
onclick="checkDelete('.$post->id.', this);"
data-token="{{ csrf_token() }}">
<i class="glyphicon glyphicon-trash icon-white"></i>
Delete
</button>';
})
->make(true);
}
return view('pages.back-end.lists.post')->with('languages', $languages);
}
This is my view
This is my yajra
$(function(){
$("#data-post").DataTable({
processing: true,
serverSide: true,
ajax:{
url: "{{ url("post") }}",
data:{ _token: "{{csrf_token()}}", languageid: languageid}
},
columns: [
{ data: 'PostDate', name: 'PostDate'},
{ data: 'PostTitle', name: 'PostTitle' },
{ data: 'PostSlug', name: 'PostTitle' },
{ data: 'action', name: 'action'}
]
});
});
You can use yajra datatables filter based upon language id reffer this - https://datatables.yajrabox.com/collection/custom-filter
or
use can do manual ajax call on button indonesia and english by passing language id and then destroy and reintiate datatable like that -
function customFilters(languageid)
{
$('#datatableid').dataTable().fnDestroy();
$('#datatableid').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
"url": url_link,
"dataType": "json",
"type": "POST",
"data":{ _token: "{{csrf_token()}}", languageid: languageid}
},
"columns": [
{ "data": "id" },
{ "data": "PostDate" },
{ "data": "PostTitle" },
{ "data": "PostSlug"},
{ "data": "LanguageID"},
{ "data": "actions" ,orderable: false, searchable: false}
]
});
}
Hope this will help you.
You have to parse the language ID with doing like this in you dataTable.php
public function language($id){
$this->language = $id;
return $this;
}
public function query(Post $model)
{
$query = Post::where('LanguageID',$this->language)->select('posts.*');
return $this->applyScopes($query);
}
then, call the dataTable manually
$('.tabPost').each(function(){
var lang_id = $(this).attr('id');
var oTable = $("#data-post" + lang_id).DataTable({
processing: true,
serverSide: true,
dom: 'Bfrtip',
order: [[0, 'desc']],
buttons: ['create',
'export',
'print',
'reset',
'reload',
'colvis',
],
ajax:{
url: "{{ url("post") }}",
data: function(d) {
d.LanguageID = lang_id
}
},
columns: [
{ data: 'id', name: 'id'},
{ data: 'PostDate', name: 'PostDate'},
{ data: 'PostTitle', name: 'PostTitle' },
{ data: 'PostSlug', name: 'PostTitle' },
{ data: 'action', name: 'action'}
]
});
$('#'+lang_id).on('click', function(e){
oTable.draw();
e.preventDefault();
});
});
and don't forget to set your controller like this
public function index(PostDataTable $dataTable, Request $request)
{
$languages = Language::where('IsActive', 1)->get();
return $dataTable->language($request->input('LanguageID'))->render('pages.back-end.lists.post', compact('languages'));
}
How do I load json data with serverside processing in a dataTable?
I'm trying to build a custom Wordpress plugin and display results from wpdb inside a dataTable.
I get a successful AJAX return call, but the dataTable only shows a "Processing..." stage and the table does not fill the rows (keeps empty).
Although I have read many(!) similar problems and answers here, any help to load data with ajax and json_encode is much appreciated.
The current code:
dahsboard.php
<table id="table-id" cellpadding="1" cellspacing="1" width="100%">
<thead><tr>
<th>h_id</th>
<th>h_subject</th>
</tr></thead>
ajax-grid-data.php
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback(){
global $wpdb;
$query = "SELECT h_id, h_subject FROM wp_tablename ORDER BY h_id limit 3";
$myrows = $wpdb->get_results($query);
foreach ($myrows as $value) {
$ResultData['h_id'] = $value->h_id;
$ResultData['h_subject'] = $value->h_subject;
$data[] = $ResultData;
}
$json_data = array(
"draw" => 1,
"recordsTotal" => 3,
"recordsFiltered" => 3,
"data" => $data,
);
echo json_encode($json_data);
die();
}
I think that the problem is in datatype formatting underneath:
dashbboard.js
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataSrc:'',
dataType : "json",
contentType: "application/json; charset=utf-8",
//dataSrc: function(data){ return data.data; },
//async : false,
//processData: true,
//accepts: {json: "application/json, text/javascript"},
success: function(data){
console.log(JSON.stringify(data)); // successful echo data objects are shown in dashboard.
},
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});
Current results
Result php file test: .../wp-admin/admin-ajax.php?action=my_action
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result ajax success function, console data:
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result dashboard table only shows: processing...
Deleting the dataSrc and success function did wonders and fills up the dataTable with data. I really appreciate the help and efforts of #bassxzero and #davidkonrad.
Ensuring that there is an answer, "on behalf of" the new version of dashboard.js:
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataType : "json",
contentType: "application/json; charset=utf-8",
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});
I use "datatables plugin for jquery" to display the results of a query in mysql.
The user can also select from a dropdown list (dateParam) and a multiselect values (conseiller) that will automatically restrict the results of the query and thus modify the table. Instead of having 5 columns, I have only 3 for example.
This is where I get the following error alert: "... requested unknown parameter 'data.1' (for example) for row 0...".
json result without selecting:
[{"name":"CONSEILLER","data":["cons1","cons2","cons3","TOTAL UNITES"]},{"name":"TOTAL UNITES","data":[1,9,2,12]}]
json result if I select some parameters:
[{"name":"CONSEILLER","data":["cons2","TOTAL UNITES"]},{"name":"TOTAL UNITES","data":[9,9]}]
Here a part of my query :
<?php
include("../dbconfig.php");
if (isset($_GET["dateParam"],$_GET["dateParam2"],$_GET["conseiller"])) {
$SQL = "
...the query...
";
$result = $dbh->prepare($SQL);
$result->execute();
} else {
$SQL = "
...the query....
";
$result = $dbh->prepare($SQL);
$result->execute();
}
$rows = array();
$rows['name'] = 'CONSEILLER';
$rows1 = array();
$rows1['name'] = 'TOTAL UNITES';
while($row = $result->fetch()) {
$rows['data'][] = $row['CONSEILLER'];
$rows1['data'][] = ($row['UNITES']);
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
header('Content-type: application/json');
print json_encode($result, JSON_NUMERIC_CHECK); // VERSION PHP >= 5.3.3
?>
Here is a part of my js :
$(document).ready(function() {
var table = $('#dt_actions_rae_conseiller').DataTable({
"paging": false,
"searching": false,
"bInfo": false,
"scrollX": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "",
"sAjaxSource": "../query/query_actions_rae_conseiller_dt.php",
"aoColumns": [
{ "data": "name" },
{ "data": "data.0" },
{ "data": "data.1" },
{ "data": "data.2" },
{ "data": "data.3" },
],
});
});
/**
* Datepicker
*/
$(function() {
var dateParam = "";
$( "#datepicker" ).datepicker({
dateFormat: "yy-mm-dd",
showAnim: 'drop',
//showOn: "button",
//buttonImage: "../icones/calendar.gif",
//buttonImageOnly: true,
onSelect: function(date){
dateParam = date;
}
});
var dateParam2 = "";
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showAnim: 'drop',
//showOn: "button",
//buttonImage: "../icones/calendar.gif",
//buttonImageOnly: true,
onSelect: function(date){
dateParam2 = date;
}
});
});
/**
* Multiselect
*/
$(function(){
$("#conseiller").multiselect({
//header: 'Choisir conseillers',
minWidth: 160,
checkAllText: 'all',
uncheckAllText: 'no',
noneSelectedText: 'Conseiller',
selectedList: 7,
/* selectedText: function(numChecked, numTotal, checkedItems){
return numChecked + ' of ' + numTotal + ' checked';
}, */
show: ["bounce", 200],
hide: ["explode", 1000]
});
//$('#projet').bind('change', function() {alert('Change'); });
});
/**
* Button
*/
$(function(){
$('button').click(function() {
var d1 = $("#datepicker").val();
var d2 = $("#datepicker2").val();
var d3 = $("#conseiller").val().join(",");
$.ajax({
url: "../query/query_actions_rae_conseiller_dt.php",
//data: {dateParam:d1, dateParam2:d2},
type: "get",
dataType: "json",
success: function(json){
table = $('#dt_actions_rae_conseiller')
.on('preXhr.dt', function ( e, settings, data ) {
data.dateParam = d1
data.dateParam2 = d2
data.conseiller = d3
})
.DataTable({
"destroy": true, // TO REINITIALISE DATATABLE
"paging": false,
"searching": false,
"bInfo": false,
"scrollX": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "",
"sAjaxSource": "../query/query_actions_rae_conseiller_dt.php",
"aoColumns": [
{ "data": "name" },
{ "data": "data.0" },
{ "data": "data.1" },
{ "data": "data.2" },
{ "data": "data.3" },
],
});
} // end ajax function
}); // end ajax
}); // end click function
}); // end function
and my php:
<table id="dt_actions_rae_conseiller" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead> // not needed ?
<tr> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
<th></th> // not needed ?
</tr> // not needed ?
</thead> // not needed ?
</table>
Thnaks for all !
Ahem, as Php . net says is not sure to test it whit a rowcount -> http://php.net/manual/en/pdostatement.rowcount.php
Because most databases won't return the number of rows.
Instead you can first run a query A with a count(*) then use a fetchColumn to have in a var the number of rows that will be obtained and then do your loop only if count > 0