I am getting this error:
DataTables warning: table id=discount_html - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
My code is:
$('#abcd').DataTable({
"processing":true,
"serverSide":true,
"destroy" : true,
"order":[],
"pageLength": 50,
"columnDefs": [
{ "orderable": false, "targets": 0 }
],
"ajax":{
url: 'abc.php',
type:"POST",
"data": function(d){
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
},
dataSrc: function (json) {
var return_data = new Array();
if(json.data.length > 0){
var obj = json.data;
console.log(obj);
return obj;
}
return return_data;
},
"columns" : [
{'data':'input'},
{'data': 'date'},
{'data': 'id'},
{'data': 'pname'},
{'data': 'cname'},
{'data': 'clname'},
{'data': 'dname'},
{'data': 'act'}
]
},
});
This is my AJAX response:
"draw":1,
"recordsTotal":1073,
"recordsFiltered":1073,
"data":[
{
"input":"<input data-id = "0" type="checkbox" name="report[]" class="allCheck" value="1234">",
"date":"2018-01-29",
"id":"1244",
"pname":"XYZ",
"cname":"adasdasd",
"clname":"NA",
"dname":"asdasdasdas",
"act":"hgh"
},
{
"input":"<input data-id = "1" type="checkbox" name="report[]" class="allCheck" value="23232">",
"date":"2018-01-29",
"id":"23232",
"pname":"aaaaa",
"cname":"asdasdsadasdsa",
"clname":"ewqweqewq",
"dname":"aaaaaaaa",
"act":"hgh"
},
and below is the HTML:
<tr>
<th><input type="checkbox" name="" id="checkAll"></th>
<th class="recept_td01">Date </th>
<th class="recept_td03">Code</th>
<th class="recept_td04">Name</th>
<th class="recept_td05">Ce</th>
<th class="recept_td05">Cli</th>
<th class="recept_td06">Doc</th>
<th class="recept_td07" id="action">Action</th>
</tr>
What am I doing wrong, that I am getting that error, tried everything but nothing seems to be working.
Related
i get an error when i try to load the dataTable again,when i click at first,it loads nicely but when i load another page and try to load the dataTable again i gain an error and the table fails to load..
..VM127:2 Uncaught TypeError: $(...).dataTable is not a function at getauctionitems
my codes
<table id="listtables" class="w3-table-all">
<thead>
<tr>
<th></th>
<th>Auction Number</th>
<th>Auction Time</th>
<th>Sale Name</th>
<th>Region</th>
<th>Sale Type</th>
<th>Auction Date</th>
<th>Status</th>
<th>Auction Name</th>
</tr>
</thead>
</table>
getauctionitems();
function getauctionitems () {
var date = new Date();
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )).toISOString().split("T")[0];
var today = new Date();
var todays = today.toLocaleTimeString();
var h = today.getHours();
var m = today.getMinutes();
h = checkTime(h);
m = checkTime(m);
var ctime = h + ":" + m;
/// console.log(ctime);
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
$('#listtables').dataTable({
"processing": true,
"responsive": true,
"serverSide": false,
"retrieve": true,
"destroy": true,
"ajax": {
url: "serverside/list.php", // json datasource
"data": {
"cdate": dateString,
"curtime":ctime
},
type: 'post', // method , by default get
},
"columns": [
{data:null,
render: function ( data, type, row ) {
return '<input type="checkbox" >';
}
},
{data: 'auctionid',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'auctionidd');
// $(td).css('display','none');
}
},
{data: 'time',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'scheduletimeid');
/// $(td).css('display','none');
}
},
{data: 'locationn',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'locationnid');
}
},
{data: 'regionn',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'scheduleregionid');
}
},
{data: 'comp',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'companyid');
}
},
{data: 'auctionndate',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'currentdateid');
$(td).css('cursor', 'pointer');
}
}
,
{data: 'date',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'statusid');
$(td).css('cursor', 'pointer');
}
}
,
{data: 'name',
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('id', 'nameid');
}
},
]
});
}
I am using data table to display large number of rows from database.I was using below code to display data fetched from database but as data started increasing,it takes lots of time to load as there are multiple joins in select query.
Below is the code which takes lots of time to load view:
<script>
$(document).ready(function() {
$('#fileData').dataTable({
"aLengthMenu": [[5,10, 25, 50, 100, -1], [5,10, 25, 50, 100, "All"]],
//"aaSorting": [[ 4, "desc" ]],
"iDisplayLength": <?php echo 5; ?>,
'bProcessing' : true,
'bServerSide' : false,
"oTableTools": {
"sSwfPath": "assets/media/swf/copy_csv_xls_pdf.swf",
"aButtons": []
},
"oLanguage": {
"sSearch": "Filter: "
},
"aoColumns": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
"aoColumns": [
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true},
{"bVisible": true}
]
}).columnFilter({ aoColumns: [
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true },
{ type: "text", bRegex:true }
]});
});
</script>
<table id="fileData" class="table table-striped table-bordered table-hover table-full-width">
<thead>
<tr>
<th>Sl.No</th>
<th>Type</th>
<th>No </th>
<th>0-15 yrs M</th>
<th>0-15 yrs F</th>
<th>15-45 yrs M</th>
<th>15-45 yrs F</th>
<th>Above 45 yrs M</th>
<th>Above 45 yrs F</th>
<th>Cumulative Since April</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<?php //if(is_object($proj_workers_report)) {
?>
<?php foreach ($nreports->result() as $index=>$row) { ?>
<tr>
<td> <?php echo $index + 1; ?> </td>
<td><?php echo $row->test1; ?></td>
<td><?php echo $row->test2; ?></td>
<td><?php echo $row->test3; ?></td>
<td><?php echo $row->test4; ?></td>
<td><?php echo $row->test5; ?></td>
<td><?php echo $row->test; ?></td>
</td>
<td></td>
</tr>
<?php
} ?>
</tbody>
</table>
After searching for solution to reduce loading time i found solution as enabling "serverSide":true.so i changed the code as below
$(document).ready(function () {
var year="<?php echo base_url() . 'reportc/new_disease_morbidity_report'; ?>";
alert(year);
var dataTable = $('#example2').DataTable({
"processing":true,
"serverSide":true,
"order":[[ 0, "desc" ]],
"ajax":{
url:"<?php echo base_url() . 'test/nreport'; ?>",
type:"POST",
data:"{'id':year}",
success: function (data) {
alert("success");
},
error: function () {
alert('error');
}
},
'language': {
"emptyTable":"No patient available"
},
"columnDefs":[
{
//"targets":[0, 3],
//"orderable":false,
},
],
});
controller:
function new_disease_morbidity_report()
{
$year = $this->input->post('id');
echo $year;
}
But issue with new code is that it is unable to call function in controller.can anyone help me out with this issue.Is there something i am missing ?
Just by adding "serverSide": true you are telling Datatable let me handle Pagination
In order to do so Datatable will append few request parameter in request API and in response you need to set few parameter to let Server Side pagination work smoothly.
You are on right track. Just need to implement correctly.
Note: As Datatable will append few parameter you need to handle them at your controller level. Add those parameters as #RequestParam. Inspect your API call to get exact parameters.
1 Datatable will add following parameter in your request POST/GET
order: asc
start: 20
length: 10
This will help you in passing LIMIT parameter in DB Query.
SELECT * FROM User LIMIT 20,10;
2 Your API should return following fields in addition
"draw": 3, // unique ID
"recordsTotal": 57, // total number of records
"recordsFiltered": 57 // total number of filtered records
You can see a sample demo here Please inspect and check request and response
Refer this answer for more detail.
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
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