ajax datatable - DataTables warning: table id=example - Cannot reinitialise DataTable - javascript

I am retrieving data from SQL to have in the table. My code is returning an error "DataTables warning: table id=example - Cannot reinitialise DataTable.For more information about this error, please see http://datatables.net/tn/3"
That's my code below. Both html and script. Help would be appreciated.
<table id="example" cellpadding="0" cellspacing="0" border="0" width="100%" class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">column 1</th>
<th scope="col">column 2</th>
<th scope="col">column 3</th>
<th scope="col">column 4</th>
<th scope="col">column 5</th>
<th scope="col">column 6</th>
<th scope="col">column 7</th>
<th scope="col">column 8</th>
</tr>
<!-- <th scope="col">Booking Ref</th>
<th scope="col">Listing</th> -->
</thead>
</table>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"employee-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#example").append('<tbody class="employee-grid-error"><tr><th colspan="16">No data found in the server</th></tr></tbody>');
$("#example_processing").css("display","none");
}
}
"columnDefs": [
{ "visible": false, searchable: true, "targets": [5,6] }
],
"order": [[ 2, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(6, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="7" style="padding:15px;">'+group+'</td></tr>'
);
last = group;
}
} );
}
} ); } );

Ok, I was missing a comma before "columnDefs":

Related

Datatable undefined error obtaining row data

I'm having an error getting the data of a row in Datatables and I can't figure it out why it's happening.
Reading the Docs, getting the row data it's as simple as:
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
console.log( table.row( this ).data() );
} );
So, I've a Jinja2 template that it's filled in server-side (in Python 3 using flask):
<table id="table" class="dataTable display responsive nowrap" cellspacing="0" width="100%">
<thead>
.....
</thead>
<tbody>
.....
</tbody>
</table>
And I initialize the Datatable with:
function createDatatable() {
$('#table').DataTable({
"select": "single",
"order": [[2, "asc"]],
"language": {.....}
}
});
}
And attach some events:
function attachEvents() {
$('#table tbody').on('click', 'td.tdCredits', function () {
var table = $('#table').DataTable();
var rowId = table.row(this).data()[0];
});
.....
}
Then I do:
$(document).ready(function() {
createDatatable();
attachEvents();
});
So, when I want to get the data of the row that I've clicked (regardless of whether it is selected or not) with this code I get an error on the console:
TypeError: table.row(...).data(...) is undefined
What I'm doing wrong? Because I can see the table rendered, with the pagination buttons and I can order the columns as well.
$(document).ready(function() {
createDatatable();
attachEvents();
});
function createDatatable() {
$('#table').DataTable({
"select": "single",
"order": [[2, "asc"]]
});
}
function attachEvents() {
$('#table tbody').on('click', 'td.tdCredits', function () {
var table = $('#table').DataTable();
var rowData = table.row(this).data();
console.log('Clicked row data: ' + rowData);
var rowId = table.row(this).id();
console.log('Clicked row id: ' + rowId);
// Other code
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="table" class="dataTable display responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th style="display: none;"></th>
<th class="text-center">Header 1</th>
<th class="text-center">Header 2</th>
<th class="text-center">Header 3</th>
<th class="text-center">Header 4</th>
<th class="text-center">Header 5</th>
<th class="text-center">Header 6</th>
<th class="text-center">Header 7</th>
</tr>
</thead>
<tbody>
<tr id="someId" class="filter">
<td style="display: none;"></td>
<td class="text-center">Cell 1</td>
<td class="text-center">Cell 2</td>
<td class="text-center">Cell 3</td>
<td class="text-center">Cell 4</td>
<td class="text-center tdCredits">Click here</td>
<td class="text-center">Cell 6</td>
<td class="text-center">Cell 7</td>
</tr>
</tbody>
</table>
You have a typo. Your variable is initialized as "table" and then you call "tabla". "Tabla" does not exist so it is undefined.
$('#table tbody').on('click', 'td.tdCredits', function () {
var table = $('#table').DataTable();
var rowId = table.row(this).data()[0];
});
Ok, I've found a trick that solved my problem and I don't need to access the '.data()'.
The problem I was having is due as you can edit some fields on each row, so the first time you click in one of the filds of the row, the row it's selected so you can use:
table.row({ selected: true }).index();
But if you click again on other field, the row is deselected and the filter selected:true doesn't work.
Doing the fiddle I discovered that Datatables uses the ID specified in
<tr id="someId" ..>
instead of some internal value. So I pass the ID value to my method and force the row to be selected:
table.row('#' + id).select();
And then I can use:
var rowIndex = table.row({ selected: true }).index();
And update the proper field instead the field of the first visible row:
table.cell({row:rowIndex, column:columnIndex}).data(newValue).draw();
Regards!
You are using array notation data[0] to access your data. But maybe you defined columns.data which means your data is an object.
you can use this.
data["nameofYourColumn"]

How to get multiple checkbox checked value in jquery datatable

On Button Click, I want to get the multiple row selected value from the datatables. From my below code, I only get the first row selected value.
function AssignVendor() {
var table = $(assignVendor).DataTable();
var data = table
.row({ selected: true })
.data();
}
<table id="assignVender" class="mp myTable table table-striped table-bordered" cellspacing="0" width="100%" ui-jq="dataTable" ui-options="dataTableOpt">
<thead>
<tr>
<th class="select-checkbox"></th>
<th>MP Name</th>
<th>MP Code</th>
<th>Vendor Name</th>
<th>Vendor Code</th>
<th>From Date</th>
<th>To Date</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="mp in MaintenanceZones">
<td></td>
<td>{{mp.MP_NAME}}</td>
<td>{{mp.MP_CODE}}</td>
<td>{{mp.REMARK}}</td>
<td>{{mp.VENDORNAME}}</td>
<td>{{mp.VENDORCODE}}</td>
<td>{{mp.VFRDATE}}</td>
<td>{{mp.VTODATE}}</td>
</tr>
</tbody>
</table>
Please help
Try this
$('#assignVender').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
function AssignVendor() {
var table = $(assignVendor).DataTable();
var data = table.rows('.selected').data();
}
Reference: https://datatables.net/examples/api/select_row.html
To Loop through the data use the following:
data = table.rows('.selected').data();
data.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );

bootstrap-table-filter-control extension doesn't work in bootstrap-table

I use bootstrap-table and would like to use table-filter-control extension. In this example you can see how to use this extension. When I want to use this extension for more columns, it doesn't work. In my example filter works only for one column.
jsfiddle
html
<table ref="mainTable" class="table table-striped table-bordered table-hover"
cellSpacing="0" id="mainTable" data-show-toggle="true"
data-show-columns="true" data-search="true" data-pagination="true" data-filter-control="true">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Customer Name" data-sortable="true" data-filter-control="select">Customer Name</th>
<th data-field="Location Type" data-sortable="true">Location Type</th>
<th data-field="Location" data-sortable="true" data-filter-control="select">Location</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Cap Corp</td>
<td>Main</td>
<td>Norwalk CT 06851</td>
</tr>
<tr>
<td></td>
<td>Cap Corp</td>
<td>Other</td>
<td>Norwalk CT 06851</td>
</tr>
<tr>
<td></td>
<td>Tel</td>
<td>Main</td>
<td>Slough SL1 4DX</td>
</tr>
<tr>
<td></td>
<td>Tel</td>
<td>Other</td>
<td>London W1B 5HQ</td>
</tr>
</tbody>
</table>
data-filed should have not spaces, try to change
data-field="Customer Name"
to
data-field="CustomerName"
I updated your jsfiddle and filter-control works.
http://jsfiddle.net/5h595r6g/9/
However it would be great to implement filter options updating to available values, as I described in this post:
bootstrap table filter-control - how to unset unnecessary values from select options
I actually put select2 boxes in the headers, and then used the params feature to pass the code to the server. I made for a much nicer solution. My code isn't with me but if you are interested in it I can pass a sample along Monday.
Edited to add example.
Basic Table
<table id='90day' class='table table-striped' data-filter-control='true'>
<thead>
<tr>
<th></th>
<th><select id='findfield' class='form-control gosearch'><option></option></select></th>
<th><select id='findwellname' class='form-control gosearch'><option></option></select></th>
</tr>
</thead>
</table>
Initialize the select2
$('#90day').on('post-header.bs.table', function () {
$('#findfield').select2({
width: '100%',
placeholder: 'Field',
allowClear: true,
SingleSelection: true,
ajax: {
url: 'selectfield90day.php?active=y',
dataType: 'json',
//delay: 250,
data: function (params) {
$('#findfield').empty();
var d = new Date();
var n = d.getTime();
return {
q: params.term,
n: n
};
},
processResults: function (data) {
return { results: data };
}
}
});
$('#findwellname').select2({
width: '100%',
placeholder: 'Name',
allowClear: true,
ajax: {
url: 'selectwellname90day.php?active=y',
dataType: 'json',
delay: 250,
data: function (params) {
$('#findwellname').empty();
var d = new Date();
var n = d.getTime();
return {
q: params.term,
field: $('#findfield').text(),
pad: $('#findpad').text(),
n: n
};
},
processResults: function (data) {
return {
results: data
};
}
}
});
//refresh on any select2 change
$('.gosearch').on('select2:close', function(){
$('#90day').bootstrapTable('refresh');
});
});
Finally table initialization
$('#90day').bootstrapTable({
url: ...,
columns:[
...
],
queryParams: function(params){
params['field']=$('#findfield').text();
params['well_name']=$('#findwellname').text();
return params;
}
});

dataTables.js not resizing properly. Table overflows window still

I am using dataTables.js from https://datatables.net/ I am also using their responsive extension , but I can not get the table to properly responsively resize. Any insight would be grand.
The table overflows the window.
If you expand it all the way out so all the columns are shown, it doesn't even start hiding columns until the 3rd column is off screen
I have created a jsfiddle with my code.
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#Table_Assets tfoot th').each(function() {
var title = $('#Table_Assets thead th').eq($(this).index()).text();
$(this).html('<input type="text" style="max-width:80px;" />');
});
// DataTable
var table = $('#Table_Assets').DataTable({
responsive: true,
"autoWidth": false,
"order": [
[13, "desc"]
],
initComplete: function() {
var r = $('#Table_Assets tfoot tr');
r.find('th').each(function() {
$(this).css('padding', 8);
});
$('#Table_Assets thead').append(r);
$('#search_0').css('text-align', 'center');
},
});
$('#Table_Assets').resize()
// Apply the search
table.columns().every(function() {
var that = this;
$('input', this.footer()).on('keyup change', function() {
that.search(this.value)
.draw();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.6/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.6/js/jquery.dataTables.min.js" type="text/javascript"></script>
<link href="https://cdn.datatables.net/responsive/1.0.6/css/dataTables.responsive.css" rel="stylesheet">
<script src="https://cdn.datatables.net/responsive/1.0.6/js/dataTables.responsive.js" type="text/javascript"></script>
<div style="max-width:100%; margin-left:auto; margin-right:auto; background-color:#c4bcbc; border-radius:15px; padding:10px; color:black" class="center">
<table id="Table_Assets" class="outerroundedborder dt-responsive" style="width:auto; margin-bottom: 15px; margin-left:auto; margin-right:auto">
<thead>
<tr style="white-space:nowrap;">
<th scope="col">Name:</th>
<th scope="col">Type:</th>
<th scope="col">Manufacturer</th>
<th scope="col">Supplier</th>
<th scope="col">Quantity</th>
<th scope="col">Serial Number</th>
<th scope="col">Location:</th>
<th scope="col">Comments</th>
<th scope="col">Computer Name</th>
<th scope="col">Room Number</th>
<th scope="col">Active</th>
<th scope="col">Tech Fee</th>
<th scope="col">Specifications</th>
<th scope="col">Deploy Date</th>
<th scope="col">User</th>
<th scope="col">Department</th>
<th scope="col">Building</th>
<th scope="col">Tickets</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width:auto;">Doom DOOM!</td>
<td>Laptop</td>
<td>HP</td>
<td>none</td>
<td>33</td>
<td>sdfg</td>
<td>sdfg</td>
<td>dfhgdfh</td>
<td>Nebulus</td>
<td>2345</td>
<td>True</td>
<td>True</td>
<td>Stuff from space</td>
<td>5/30/2015</td>
<td>Michaels | Joey</td>
<td>Staff</td>
<td></td>
<td>
<br />
<div class="grey">No tickets found</div>
</td>
</tr>
<tr>
<td style="width:auto;">Dr. Von Doom</td>
<td>Laptop</td>
<td>HP</td>
<td>none</td>
<td>0</td>
<td>123412341234</td>
<td>Dr. Doom's Lair</td>
<td></td>
<td>Spiderman</td>
<td>42</td>
<td>True</td>
<td></td>
<td>Spidey sense is tingling. ^_^</td>
<td>6/18/2015</td>
<td>Michaels | Joey</td>
<td>Staff</td>
<td>AIC Faculty</td>
<td>
<br />
<div class="grey">No tickets found</div>
</td>
</tr>
</tbody>
<tfoot>
<tr class="sortbottom">
<th scope="col">Name:</th>
<th scope="col">Type:</th>
<th scope="col">Manufacturer</th>
<th scope="col">Supplier</th>
<th scope="col">Quantity</th>
<th scope="col">Serial Number</th>
<th scope="col">Location:</th>
<th scope="col">Comments</th>
<th scope="col">Computer Name</th>
<th scope="col">Room Number</th>
<th scope="col">Active</th>
<th scope="col">Tech Fee</th>
<th scope="col">Specifications</th>
<th scope="col">Deploy Date</th>
<th scope="col">User</th>
<th scope="col">Department</th>
<th scope="col">Building</th>
<th scope="col">Tickets</th>
</tr>
</tfoot>
</table>
</div>
I have the same issue, I'm using the jquery DataTables 1.10.7 and the extension Responsive 1.0.6, I solved by adding a line in the "dataTables.responsive.js" in the _resize function, about line 560.
Add the next line at the end of the function:
$(dt.table().node()).removeAttr('style');
That should work.
The function most look like this:
_resize: function() {
var dt = this.s.dt;
var width = $(window).width();
var breakpoints = this.c.breakpoints;
var breakpoint = breakpoints[0].name;
var columns = this.s.columns;
var i, ien;
// Determine what breakpoint we are currently at
for (i = breakpoints.length - 1; i >= 0; i--) {
if (width <= breakpoints[i].width) {
breakpoint = breakpoints[i].name;
break;
}
}
// Show the columns for that break point
var columnsVis = this._columnsVisiblity(breakpoint);
// Set the class before the column visibility is changed so event
// listeners know what the state is. Need to determine if there are
// any columns that are not visible but can be shown
var collapsedClass = false;
for (i = 0, ien = columns.length; i < ien; i++) {
if (columnsVis[i] === false && !columns[i].never) {
collapsedClass = true;
break;
}
}
$(dt.table().node()).toggleClass('collapsed', collapsedClass);
dt.columns().eq(0).each(function(colIdx, i) {
dt.column(colIdx).visible(columnsVis[i]);
});
$(dt.table().node()).removeAttr('style');
},
Best regards.

How to hide/display rows in datatables?

I am trying to hide/display certain rows based on data from a hidden column. my table structure looks like:
<table id="agent_search" cellpadding="0" cellspacing="0" border="0" class="table table-striped">
<thead>
<th>Agent ID</th>
<th>Agent Name</th>
<th>ID Number</th>
<th>Mobile Number</th>
<th>Team Name</th>
<th>Status</th>
<th></th>
</thead>
</table>
I am trying to hide/show records based on the Status column, using a checkbox. If the status == DEREGISTERED I want to exclude it from the table (unchecked checkbox).
I adapted my code from what was done here:
$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
// does not run this
console.log("GOTHRERE");
if ('agent_search' == oSettings.nTable.id) {
// console.dir(oSettings);
console.dir(aData);
var dereg = aData[5];
console.log(dereg);
if (dereg == "DEACTIVATED"){
return $('#toggle_deregistred').is(':checked');
} else {
return $('#toggle_deregistred').is(':not:checked');
}
}
return true;
});
I have tried using $.fn.dataTableExt.afnFiltering witch is used for custom filtering, only to find that I can not do it. It was once possible in previous versions of dataTables as in this case , but as it turns out it was a bug that allowed it to be possible :|.
Is there a way that I can filter out rows based on if their Status with the use of a checkbox? or is there something in the api I can use that I have over looked?
UPDATE:
I have made a jsfiddle in which it is working, how ever in the process of adapting my code to put it in jsfiddle, I noticed that it is bServerSide that is causing the $.fn.dataTableExt.afnFiltering not to work. Is there a work around or another way to user Server-side processing?
I found an alternate way to the checkbox of hiding/displaying.
I use Bootstrap 3 tabs to apply different filters:
<ul class="nav nav-tabs form-tabs" id="search-tabs">
<li id="basic-list" class="active"><a data-toggle="tab" data-dtname="all" href="#all">All</a></li>
<li class="" id="dereg-list"> <a data-toggle="tab" data-dtname="dereg" href="#dereg">Deregistered</a></li>
</ul>
<br>
<div class="tab-content">
<fieldset id="all" class="tab-pane active">
<table id="agent_search" cellpadding="0" cellspacing="0" border="0" class="table table-striped">
<thead>
<th>Agent ID</th>
<th>Agent Name</th>
<th>ID Number</th>
<th>Mobile Number</th>
<th>Team Name</th>
<th>Status</th>
<th></th>
</thead>
</table>
</fieldset>
<fieldset id="dereg" class="tab-pane ">
<table id="dereg_agent_search" cellpadding="0" cellspacing="0" border="0" class="table table-striped">
<thead>
<th>Agent ID</th>
<th>Agent Name</th>
<th>ID Number</th>
<th>Mobile Number</th>
<th>Team Name</th>
<th>Status</th>
<th></th>
</thead>
</table>
</fieldset>
</div>
I first initialize the table on the first tab all which uses bServerSide=true and for the other table(when I switch to the other tab) I do:
$('#search-tabs a').click(function(e) {
e.preventDefault();
$(this).tab('show');
if (this.dataset["dtname"] == "all") {
oTable.fnDraw();
} else if (this.dataset["dtname"] == "dereg") {
var data = $("form").serialize();
$.post(
url, data
).success(function(data){
console.log(data.aaData);
kTable = $('#dereg_agent_search').dataTable( {
"sScrollY": "250px",
"data": data.aaData,
"destroy" : true,
"sDom": "<'row'<'col-sm-6'><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'>>S",
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [ 6 ],
"sWidth":"150px",
"mRender": function( data, type, full ){
return "<div class='btn-group'><a href="+full[6][0]+" class='btn btn-default btn-sm'>View</a><a href="+full[6][1]+" class='btn btn-default btn-sm'>Edit</a></div>"
}
},
{
"bSortable": true,
"aTargets": [ 0 ],
"sWidth":"150px",
"mRender": function( data, type, full ){
if (full[5] == "DEACTIVATED"){
return "<a href="+full[6][0]+" class='DEACTIVATED'>"+data+"</a>"
} else{
return ""+data+""
}
}
},
{"aTargets": [ 4 ], "sWidth":"250px" },
{"aTargets": [ 5 ], "bVisible":false},
],
"bDeferRender": true,
"bStateSave": true
} );
});
kTable.fnDraw();
}
});
Notice that I get the data to populate the table from the server - using a jQuery $.post request, and then I use datatables' data attribute to populate the table.
I hope This can Help someone.

Categories

Resources