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
Related
I'm developing an Event Calendar in PHP, saving the data in MS-SQL.
I was successful in sending the data to the database, however, I'm not able to fetch the data from it.
Here's what I've done so far:
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true,
events: "all_events.php",
displayEventTime: false,
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Detail:');
if (title) {
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$.ajax({
url: 'add_event.php',
data: 'title=' + title + '&start=' + start + '&end=' + end,
type: "POST",
success: function(data) {
displayMessage("Added Successfully");
}
});
calendar.fullCalendar('renderEvent', {
title: title,
start: start,
end: end,
allDay: allDay
}, true);
}
calendar.fullCalendar('unselect');
}
});
});
all_events.php
<?php
require_once("connection.php");
$conn = DB::databaseConnection();
$json = array();
$sql = "SELECT * FROM Events ORDER BY id";
$result = $conn->prepare($sql);
$result->bindParam(':id', $id);
$alldata = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
array_push($alldata, $row);
}
echo json_encode($alldata);
?>
I'm just getting a '[]' in the console. No other error and the calendar is blank, it is not displaying any data from the database.
I Have used this ignited_datatables https://github.com/IgnitedDatatables/Ignited-Datatables in my CodeIgniter project. It successfully returns data from the database. But the main problem is that when I add a new record the newly inserted data is not shown in the table automatically and when I refresh the page then the newly inserted data is then shown in the table. so I want to show that data automatically through ajax and I have not to refresh the page.
My View
<div class="box-body table-responsive">
<table id="Slider_table" class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>item_Price</th>
<th>Description</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- /.box-body -->
This Script is Inside the View
$(document).ready(function() {
$("#Slider_table").dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxDataProp": "data",
"fnServerData": function(sSource, aoData, fnCallback){
$.ajax({
"dataType": "json",
"type" : "POST",
"url" : "'.base_url().'Home/items_list/list",
"data" : aoData,
"success" : function(res){
fnCallback(res);
}
});
}
});
});
I think you need to use draw() method after success in order to have the table's display updated.
table.row.add( {
//you dynamic data
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$3,120",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
} ).draw();
as per documentation. please refer draw()
You can use ajax.reload() method
var i=1;
function datatable()
{
$("#myTable1").dataTable().fnDestroy();
$('#myTable1').DataTable({
"ordering": true,
"searching": true,
"bPaginate": true,
ajax: 'myajaxURL.php',
columns : [
{ "render": function ( data, type, full, meta ) { return i++; }
},
{"data": "col1"},
{"data": "col2"},
{"data": "col3"},
]
});
}
function insertData {
//after each insertion do this
var i=1;
$('#myTable1').DataTable().ajax.reload();
//after each insertion do this
}
$(document).ready(function () {
datatable();
});
i always did this in every view of my page
var table;
table = $('#Slider_table').dataTable({
"bPaginate": false,
"bLengthChange": false,
"bFilter": false, // OPTIONAL
"bSorting": false,
"bInfo": true,
"bAutoWidth": false,
});
function getData() {
$.ajax({
type: "POST",
url: "<?php echo base_url('your_controler/function_name'); ?>",
data: aoData,
error: function(response) {
alert('Error')
},
success: function(response) {
setTable(response);
}
});
}
function setTable(response) {
var obj = JSON.parse(response);
var t = $('#Slider_table').dataTable();
t.clear().draw();
$.each(obj, function(index, value) {
var a = value.a;
var b = value.b;
var c = value.c;
t.row.add([
a,
b,
c
]).draw(false);
})
}
So everytime you reload or insert a new data,you just have to call getData() function to load a new set of data you just insert. And t.clear().draw(); will clear all data from tbody,and replaced it with new one . Hope this helps
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
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");
}
},
});
});
Im having problems getting my datatable to refresh. I have a button which calls an update script and a confirmation message before it does anything. This all works fine but, I would like the table to refresh to get the new results. Here is what I have so far.
function unapprove_link(data)
{
var str = $(this).attr('title');
var answer = confirm("Are you sure you want to UNAPPROVE this lead?");
if (!answer) return false;
$.post("actions/unapprove-lead.php",
{'lead_id': data},
function()
{
oTable.fnClearTable(0);
oTable.fnDraw();
}
);
}
Here is my full code:
$(document).ready(function()
{
/* // Unapprove Lead Alert
$('.unapprove').live('click', function() {
var str = $(this).attr('title');
var answer = confirm("Are you sure you want to UNAPPROVE this lead?");
oTable.fnDraw();
if (!answer) return false;
});
// Delete Lead Alert
$('.delete').live('click', function() {
var str = $(this).attr('title');
var answer = confirm("Are you sure you want to DELETE this lead?");
oTable.fnDraw();
if (!answer) return false;
});
*/
var anOpen = [];
var oTable = $('#example').dataTable
({
'bProcessing': true,
'aaSorting': [[1,'asc']], // sorts date by default.
'iDisplayLength': 10,
'bJQueryUI': true,
'bStateSave': true,
'bServerSide': true,
'sAjaxSource': 'ajax/pc-ajax-table.php',
'fnServerData': function(sSource, aoData, fnCallback)
{
aoData.push( { "name": "from_date", "value": $( "#from" ).val() },
{ "name": "to_date", "value": $( "#to" ).val() } );
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
},
'aoColumns':[
{"bVisible": false, "bSortable": false, "bSearchable": true},
{"fnRender": format_ddmmyyyy}, // renders the date as dd/mm/yyyy
null, // name
null, // lead location
null, // course type
{"bVisible": false, "bSortable": false, "bSearchable": true},
{"bVisible": false, "bSortable": false, "bSearchable": true},
{"bVisible": false, "bSortable": false, "bSearchable": true},
{"bVisible": false, "bSortable": false, "bSearchable": true},
null,
null,
{"sClass": "control", "bSortable": false, "bSearchable": false},
{"bSortable": false, "bSearchable": false},
{"bSortable": false, "bSearchable": false}]
});
// for adding a details box
$('#example td.control').live( 'click', function () {
var nTr = this.parentNode;
var i = $.inArray( nTr, anOpen );
if ( i === -1 ) {
$('img', this).attr( 'src', "../images/details_close.png" );
var nDetailsRow = oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push( nTr );
}
else {
$('img', this).attr( 'src', "../images/details_open.png" );
$('div.innerDetails', $(nTr).next()[0]).slideUp( function () {
oTable.fnClose( nTr );
anOpen.splice( i, 1 );
} );
}
} );
function fnFormatDetails( oTable, nTr )
{
var oData = oTable.fnGetData( nTr );
var sOut =
'<div class="innerDetails">'+
'<div style="padding:6px; background-color:#FFF;">Enquiry: <span style="color:#2663A4;">'+oData[8]+'</span></div>'+
'<div style="padding:6px; background-color:#FFF;">Email: <span style="color:#2663A4;">'+oData[5]+'</span></div>'+
'<div style="padding:6px; background-color:#FFF;">Phone: <span style="color:#2663A4;">'+oData[6]+'</span></div>'+
'<div style="padding:6px; background-color:#FFF;">IP Address: <span style="color:#2663A4;">'+oData[7]+'</span></div>'+
'<div style="padding:6px; background-color:#FFF;">Lead ID: <span style="color:#2663A4;">'+oData[0]+'</span></div>'+
'<div style="height:6px;"></div>'+
'<div class="light-blue-underline-main" style="margin:0px;"></div>'+
'<div style="height:6px;"></div>'+
'</div>';
return sOut;
}
// For clicking and selecting the date ranges
$("button").button().click(function() {
oTable.fnDraw();
});
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy',
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});
// Take date from mysql, formatted yyyy-mm-dd, and return as dd/mm/yyyy
function format_ddmmyyyy(oObj) {
var sValue = oObj.aData[oObj.iDataColumn];
var aDate = sValue.split('-');
return aDate[2] + "/" + aDate[1] + "/" + aDate[0];
}
// Highlight Rows
$("tbody tr").live("mouseover", function(){
$(this).children().addClass("highlighted");
});
$("tbody tr").live("mouseout", function(){
$(this).children().removeClass("highlighted");
});
// Actions for Unapprove button
function unapprove_link(data)
{
var str = $(this).attr('title');
var answer = confirm("Are you sure you want to UNAPPROVE this lead?");
if (!answer) return false;
$.post("actions/unapprove-lead.php",
{"lead_id": data},
function(data)
{
oTable.fnDraw();
}
);
}
/*// Actions for Delete button
function delete_link(data)
{
$.post("actions/delete-lead.php",
{'lead_id': data},
function(data)
{
oTable.fnDraw();
}
);
}
*/
Calling oTable.fnDraw() will cause the refresh for sure. You are doing $.post, I would change it to .$ajax, also, you don't seem to be doing anything with the data returned from the post operation. Remember, DataTable expects an oData object somewhere in the response if you expect it to rebind the data.
In fact, datatable expects a lot more, you need to return the number of items in total, the number being displayed on the page, etc.