Delete rows in Datatable before destroying - javascript

I am initializing a Datatable each time the function lds is called. The function lds pulls data for table and appends the relevant HTML by
$('#tablebody').html(data);
After that I am initializing a datatable like so,
$('#rTable').Datatable({
paging:false,
destroy: true
});
This solves the problem of the error "Datatables cannot be initialized" if I call the lds function again. But the old rows are retained that were appended previously. I have tried the following approaches:
Assigned var table to the initialization of Datatable and put table.empty() at the beginning of lds. But as expected, the table variable is undefined.
Tried to delete row(0) while length > 0 but that messes the table and deletes the as well.
Tried ('#rTable').empty() but due to this Datatables throws an error d[i] not defined.
What is an approach I can take to empty the rows each time the function lds is called.

Destroy an existing table on a button click
var table = $('#myTable').DataTable();
$('#tableDestroy').on( 'click', function () {
table.destroy();
} );
Reload a full table description from the server, including columns:
var table = $('#myTable').DataTable();
$('#submit').on( 'click', function () {
$.getJSON( 'newTable', null, function ( json ) {
table.destroy();
$('#myTable').empty(); // empty in case the columns change
table = $('#myTable').DataTable( {
columns: json.columns,
data: json.rows
} );
} );
} );

Related

When I delete data from jquery data-table it still showing in grid until refresh

I tried that table automatically refresh but it does not until I manually reload the whole page.
When I delete data this exception occur in console on .draw();
Uncaught TypeError: $(...).draw is not a function
at sortTableAfterdelete
function ConfirmDelteTraining(id) {
$.post("/Franchise/deleteTraining", { TrainingId: id }, function (data) {
if (data) {
debugger;
var t = $('#trainingGrid').DataTable();
t.row($('#trainingGrid').find('[data-id=' + id + ']')).remove().draw();
//Set order after deleting state
sortTableAfterdelete();
}
function sortTableAfterdelete() {
if ($("#trainingGrid tbody tr td").length == 1) {
$('#trainingGrid').DataTable().search(this.value).draw();
}
};
remove .draw() and try.
draw will not come herer.

Datatables has only 10 rows accessible outside the DataTables creation function

I am using Django and in one of my tamplates I use datatables (1.10.19) to display my table data.
This is how my code looks like:
$(document).ready( function () {
table = $('#mytable').DataTable({
"pagingType": "full_numbers",
data: dataSet,
columns: [
{ title: "Naslov zahtjeva" },
{ title: "Datum slanja" },
{ title: "Status" },
{ title: "Rok Izvršenja." },
{ title: "Id zahtjeva" },
],
"fnCreatedRow": function(row, data, index){
$(row).addClass("clickable-row");
$(row).attr('data-href', data[4]);
$(row).addClass("table_row_point");
},
});
Problem occurs at the line -> $(row).attr('data-href', data[4]);
I have a different function that is suposed to use that 'ID' from 'data-href' attribute in order to go to another page like this
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
});
Thing is it works fine for first 10 rows, and when I try 'console.log( this );' I get
Only for the first 10 rows, and it acts like other 3000 don't even exist, I believe it is connected to the default value of 10 rows that appear, but it makes no sense to me for data to be displayed normally, but the 'tr' element not to exist for all, but 10 of them.
Note: When I place this function into DataTable creation code (1st snippet) it shows all the tr elements
$('#mytable tbody').on( 'click', 'tr', function () {
console.log( this );
} );
If someone has any idea it would be much appreciated
fnCreatedRow function is executed everytime datatable creates the <tr> element in the dom. Since you have enabled pagination, function is run only on the <tr> elements created at the time. If you move on to next page, you'll see that console prints next set of rows.
By the way I think createdRow is preferred over old fnCreatedRow naming convention. https://datatables.net/reference/option/createdRow

Datatable update from another component

I'm using the datatables table plugin for jquery. I have another component that uses Ajax to retrieve an object from the server. I'd like to update the database with this object. I'm struggling on how to piece this together. The Ajax returns an object that is in the format that the datatable will accept for data. But how can I update the datatable from another components Ajax call? I'm using python flask and jinja2 templating. Here is the javascript as it currently exist:
$(function() {
var container = document.getElementById('visualization');
var items = new vis.DataSet({{documents|safe}});
var options = {};
var timeline = new vis.Timeline(container, items, options);
timeline.on('select', function (properties) {
$.getJSON('/getDependencyHistory', {
uuid: properties.items[0]
}, function(data) {
console.log("Place this into the datatable");
});
return false;
});
});
$(document).ready(function() {
var table = $('#example').DataTable();
});
here is a really simple one that "fools" the ajax call.
go to http://live.datatables.net/nesadivo/1/edit
Click on Run With JS button to initialize everything. Click on the go button to go get the data
$(document).ready(function() {
// created a global variable for the datatable to us to find the data
var dtData = null;
// On the button click, use regular ajax to get the data
$("#btnGo").on("click", function(){
$.ajax({url:"http://live.datatables.net/examples/server_side/scripts/server_processing.php",
success:function(cData){
// on success, set the global variable then reload table
dtData = JSON.parse(cData);
$('#example').DataTable( ).ajax.reload();
},
error:function(err){debugger;}} );
});
// initialize the table on page load
$('#example').DataTable( {
"ajax": function(a,callback,c){
callback(dtData);
}
});
});

Custom rendering when using server side processing

I was wondering if the rendering of the table after receiving an ajax response can be modified. This seems related to the render function described here: https://www.datatables.net/manual/orthogonal-data.
My server returns Data like
{
"name":
{
id: "123456",
value: "Tiger Nixon"
}
}
I want to add to each name cell the id of the name as data-attribute or as id for the td and want to add a .on( "click", handler ) for each cell.
Is this possible?
Thanks in advance
You can use DT_RowData or DT_RowAttr (requires DataTables 1.10.5 or higher) parameters in your returned data to assign attributes to <tr> element which you can later retrieve in click handler, see Server-side processing chapter in the manual.
Alternatively you can use render method but it may not be as effective. I assumed below that index of your name column is 0 and that you want to set data-id attribute.
var table = $('#example').DataTable({
"columnDefs": [{
"data": "name.value",
"targets": 0,
"render": function ( data, type, full, meta ) {
if(type === 'display'){
$('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
}
return data;
}
}]
});
You can add click event handler using the code below:
$(document).ready(function(){
var table = $('#example').DataTable({
// Define DataTables initialization options here
});
$('#example tbody').on('click', 'td', function(){
// Use table to access various API function
//
// For example:
// var data_cell = table.cell(this).data();
});
});
This is possible by using the columns.createdCell function.
The answer of Gyrocode is correct for an old DataTables version.

Row Count on DataTable Does Not Refresh

I have an Alloy UI DataTable created when a search form is submitted - this table displays x amount of records as well as the number of records returned
var dataTable = new Y.DataTable({
columns: columns,
footerView: Y.FooterView,
scrollable: 'y',
height: '95%',
footerConfig: {
fixed: true,
heading: {
colspan: 5,
content: "Number of Records : {row_count}" //returns number of rows
}
});
On Submit:
node.on( //search button
'click',
//make request
success: function(e) {
//do some stuff
dataTable.set('data', responseText); //adds data to DataTable
//function to refresh {row_count}?
}
When the search form is resubmitted, the DataTable is reloaded, however {row_count} does not get refreshed to match records returned. Is there a simple way to reload this count after each request?
You can count the rows like this and try refresh your {row_count} with Y.one('#??').set('value',xyz) on your own
node.on( //search button
'click',
//make request
success: function(e) {
var row_count = 0;
//do some stuff
dataTable.set('data', responseText); //adds data to DataTable
//function to refresh {row_count}?
row_count = dataTable.get('data').size();
// something like this --> Y.one('#??').set('value',row_count);
}

Categories

Resources