Related
I'm trying to fetch big amounts of data from a MySQL-database. Therefore I don't want the user to fetch all data at once, cause this could potentially break the DB-server. Yet when I set the jQuery Datatable options, it doesn't seem to be affected by the DisplayLength I set. When I change the amount of items to show, the box and the pagination at the bottom do change, yet the data remains the same.
I've tried to add an invisible field at the and of the columns, which seemed to help in the past. For this problem it didn't though.
$.post("index.php?action=getDataStructurePropsFromSensorId", {
sensorId : sensorId
}, function(data) {
dataProps.push({ "mDataProp": "data_entry_id" });
data.forEach(function (item, i) {
var th = i;
$('#data-th-'+th).html(item['struct_property_label']);
$('.data-th').each(function () {
if ($(this).html() == '') {
$(this).hide();
} else {
$(this).show();
}
});
dataProps.push({ "mDataProp": "data_value_"+i.toString(), "bSortable": false,"bSearchable": false});
});
dataProps.push({ "mDataProp": "data_entry_created_at", "bSortable": false, "bSearchable": false });
dataProps.push({ "mDataProp": "data_entry_id", "bVisible": false });
var obj2 = {
"bStateSave": true,
"bProcessing": true,
"bRetrieve": true,
"bServerSide": true,
"sAjaxSource": "index.php?&action=getSensorData&sensor_id="+sensorId+"&from="+from+"&till="+till,
"iDisplayLength": 5,
"aLengthMenu": [[5, 10, 25, 50, 100, 200], [5, 10, 25, 50, 100, 200]],
"aoColumns": dataProps,
"fnRowCallback": function( nRow, aaData, iDisplayIndex ) {
return nRow;
},
"aaSorting": [[0, 'asc']],
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fnInitComplete": function (oSettings, json) {
},
"fnDrawCallback": function () {
}
};
oDataTableOverview = $('#sensor_data_dt').dataTable(obj2);
}, "json");
I'm expecting 5 records, depending on the page and the selection in the pagination amount box. Does anyone have an idea why I'm getting all data instead of 5 records?
Which datatables version are you using? For datatables with version 1.10 and above, please use the "pageLength" instead of "iDisplayLength"
$('#example').dataTable( {
"pageLength": 5
} );
In My case i fix it
datatable_object.settings()[0]._iDisplayLength = -1;
datatable_object.draw();
Using Server side processing, with Ignited Datatables, getting the same result set no mater the action I take no other errors are returned.
The page example: I haven't given the server a name can't include link..
> http://104.200.17.5/BotController
JS code
$(document).ready(function() {
var oTable = $('#big_table').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": 'BotController/IpTest',
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayStart ":20,
"oLanguage": {
"sProcessing": "assets/images/ajax-loader_dark.gif'>"
},
"fnInitComplete": function() {
//oTable.fnAdjustColumnSizing();
},
'fnServerData': function(sSource, aoData, fnCallback)
{
// console.log(fnCallback);
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
}
} );
});
The server call:
public function IpTest()
{
//ob_clean();
$this->datatables->select('ID,Voting_ID,User_IP,X_IP')
->unset_column('ID')
->from('User_IP_check');
echo $this->datatables->generate();
}
The solution is to use this, and bind all your column names into mData.
"aoColumns": [{
"mData": "col_name_1"
}, {
"mData": "col_name_2"
}, {
"mData": "col_name_3"
}, {
"mData": "col_name_3"
}
],
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
As of now I am passing parameter along with URL in ajax call of data table.
But I want to pass it as POST method, please anyone one help me regarding parameter passing in post method, here's my trial code:
// Sending through GET
var $table = $('#example').dataTable(
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": 'getResult.php?formName=afscpMcn&action=search&mcn_no='+mcnNum+'&cust_nm='+cust_num+'&emp_id='+emp+''
});
Just pass it like a normal jQuery ajax in POST fashion.
The structure should look like this:
ajax: { type: 'POST', url: <path>, data: { your desired data } }
Example:
var $table = $('#example').dataTable(
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": {
'type': 'POST',
'url': 'getResult.php',
'data': {
formName: 'afscpMcn',
action: 'search',
// etc..
},
}
});
In PHP, just access the POST indices as usual (just the straightforward approach):
getResult.php
$form_name = $_POST['formName'];
// the rest of your values ...
DataTables manual entry
You can try this way:
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"data": function ( d ) {
d.extra_search = $('#extra').val();
}
}
});
https://datatables.net/reference/option/ajax.data
$("#tbl").dataTable({
oLanguage: {
sProcessing: '<div id="loader"></div>'
},
bProcessing: true,
"bServerSide": true,
"iDisplayLength": pageSize,
"sAjaxSource": " /PurchaseOrder/AddVendorItems", // url getData.php etc
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
aoData.push({ "name": "where", "value": ID +" AND ISNULL(IsFinal,0) = "+ ($("#chkFinal").bootstrapSwitch('state') == true ? 1 : 0) });
aoData.push({"name": "PackIDFK", "value": $("#PackIDFK").val()}) //pushing custom parameters
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
} });
This is real time example.The aoData contains all the parameters which is required on server side and you can also push your own custom parameters
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.