How can I refresh a datatable inside a div using JavaScript? - javascript

Here is my code:
oTable2 = $('#BigData2').dataTable({
"bLengthChange":false,
"bPaginate":false,
"oLanguage": {
"sZeroRecords": "No records found"
},
"sAjaxSource":'StatusSrv',
// "sDom":'RCT<"clear">lfrtip',
//"aoColumnDefs":[{}]
})
var auto_refresh = setInterval(
function (){
$('#Status_Table').fadeOut('slow').load('SupplyPlanning.jsp
#oTable2.fnDraw()').fadeIn("slow");
}, 6000);
<div id="Status_Table" class="chartFloatLeftInner">
<table id="BigData2" >
<thead >
<tr>
<th><input type="checkbox" onClick="checkall()" name="maincheck" id="maincheck"/></th>
<th title="REQ_NO">REQ_NO</th>
<th title="Retailer Partner number">Retailer num</th>
<th title="STATUS">OVERALL_STATUS</th>
</tr>
</thead>
<tbody></tbody>
</table>
I want to refresh my datatable in a particular time interval so that I am using fndraw but it only redraws the table with the old data. If I insert new data in the database, the new data is not shown after refresh; it shows only the old data.

Probably you would need to add the "bDestroy": true attribute to your datatable code which allow you to rebuild it otherwise once created you can not load it with new data.

Try using append:
$('#Status_Table').append( your table in here);
It work for me

Related

How to render angular ng if/show within database

current I am working with a combination of datatables + angularjs. I'm following documentation here. https://l-lin.github.io/angular-datatables/archives/#!/gettingStarted
My table is rendering and getting populated with angularjs code. The issue I am coming across is I only want the photo text to appear only when it exist. When I inspect the element, ng-hide is always set. It'll appear fine if I remove ng-if.
Code
<table datatable="ng" class="contact-grid-table row-border" dt-options="vm.dtOptions2" dt-column-defs="vm.dtColumnDefs" dt-instance="dtInstanceCallback" id="tableId">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in vm.contacts">
<td>{{contact.firstName}}</td>
<td>{{contact.lastName}}</td>
<td><span ng-if="contact.photo">{{contact.photo}}</span></td>
</tr>
</tbody>
</table>
I also tried the suggestion here ng-show not working in datatables columns but my table will no longer load. Page just freezes.
May I ask if there's any suggestions on how to get ng-if/show to work with datatables.
vm.dtOptions2 = DTOptionsBuilder.newOptions()
.withOption('createdRow', function (row, data, dataIndex) {
// Recompiling so we can bind Angular directive to the DT
$compile(angular.element(row).contents())($scope);
})
.withOption('headerCallback', function (header) {
if (!vm.headerCompiled) {
// Use this headerCompiled field to only compile header once
vm.headerCompiled = true;
$compile(angular.element(header).contents())($scope);
}
})
.withPaginationType('full_numbers').withOption('responsive', true)
.withColReorder()
.withColReorderOrder([0,1, 2,3])
.withScroller()
.withOption('bFilter', false) // for search box
.withOption('bInfo', false) // for showing counts at the bottom
.withOption('deferRender', true)
.withOption('scrollY', 200)
// Set order
// Fix last right column
.withDisplayLength(2)
.withFixedHeader({
bottom: false
});

Permanently reverse the order of a DataTable in jQuery?

Let's say I have a Data Table like so:
<table id="history" class="display">
<thead>
<th>Player</th>
<th>Word</th>
<th>Value</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
I have a function that receives a payload from the server and adds a row to the datatable with the relevant information
var history_data_table = $('#history').DataTable({
"pageLength": 5,
"searching": false,
"bLengthChange": false,
"language": {
"emptyTable": "Words that you discover will appear here."
}
});
function liveRecv(word_payload) {
history_data_table.row.add([word_payload.id_in_group,
word_payload.word,
word_payload.word_value,
word_payload.message]
).draw();
Naturally, this will add the row to the end of a paginated table. This table is a list of transactions in a game, and I want to present the most recent transactions to the user, such that every row that's added is added to the top of the data-table. What is the easiest way to achieve this?
You could try this method using jQuery
$('#history tr:first').after("<tr role="row"><td></td><td>add you own row</td></tr>");
or you could use DataTables inner function to access the array of rows
var history_data_table = $('#history').dataTable();
var DisplayMaster = history_data_table.fnSettings()['aiDisplayMaster'];
var tableapi = history_data_table.api();
var getlastrow = DisplayMaster.pop();
DisplayMaster.unshift(getlastrow);
tableapi.draw(false);

jQuery Datatables Reload

I'm facing an issue using the Datatables plug-in regarding a table reload after the user adds a row.
I'm receiving some JSON data as part of a webservice call, after successfully receiving that data, I am calling a function that will build the table rows and append them to the tbody of the datatable as follows:
const buildTableRows = obj => {
const table = document.querySelector('#participantes tbody');
table.innerHTML = "";
for (item of obj) {
const tableRow = `<tr id="${item.ContactoId}" data-contributos="${item.Contributos}" data-updated="false" class="participante-row"><td><i class="material-icons">arrow_right</i>${item.Nome}</td><td class="contributos"><input value="${item.Contributos}">&nbsp&nbsp&nbsp<i class="material-icons delete">delete_forever</i></td></tr>`;
table.insertAdjacentHTML('beforeend', tableRow);
}
}
After this, I call another function responsible for initializing the Datatable and saving it to a global object for future reference:
const buildDataTable = () => {
const table = $('#participantes').DataTable({
"pagingType": "simple_numbers",
"pageLength": 4,
"lengthChange": false,
"columnDefs": [{
"targets": 1,
"orderable": false
}],
responsive: true
});
controlObj.datatable = table;
}
In my HTML I have a dynamically generated select element which lets the user add a row to the table. When the user adds the row, those two functions get called again. I can see the new row in my data structure but the table doesn't get refreshed without a page reload. I went through the plugin docs and tried to use the destroy method, rows.add(), clear(), draw() etc.. but nothing seems to work for me. The table structure is already in the DOM, I just need to reload the table. Any help would be much appreciated
Datatable cannot be clear and redraw for updated HTML DOM for table but it has to be inserted using JSON array.
To refresh it after change in DOM, you need to destroy the table and re-initalize it.
See below example where on click of ADD button I have added new row and reiniitalized the table but before that I have destroyed it.
$(document).ready(function() {
//Initialize the table and save it in a variable.
var table = $('#example').DataTable();
var id = 0;
$('#add').on('click', function(){
table.destroy();
//add row to the table
var html = '<tr><td>' + id + '</td><td>First Name' + id + '</td><td>Last Name' + id + '</td></tr>';
//console.log(html);
$('#example tbody').append(html);
id++;
table = $('#example').DataTable();
});
} );
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.jqueryui.min.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td>00</td>
<td>First</td>
<td>Last</td>
</tr>
</tbody>
</table>
Click Button to Add row : <input id="add" value=" ADD " type="button">
Yes you can use DataTable api. without destroying table you just need a function.
$(document).ready(function() {
var dt = $('#example').DataTable();
$('#addRow').click(function () {
var rowHtml = $("#newRow").find("tr")[0].outerHTML
console.log(rowHtml);
dt.row.add($(rowHtml)).draw();
});
});
here is working example

How to get information from datatable - javascript - MVC

I have created an ASP.net MVC app and I have created a DataTable [DataTable.net] as follows:
<table id="invoiceTable">
<thead>
<tr>
<th>Invoice ID</th>
<th>Date</th>
<th>Reciept Date</th>
<th>Category</th>
<th>Total Value</th>
<th>Invoice Ref</th>
<th>Client</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#{
foreach (FreeAgentApp.Models.CustomInvoice _invoice in ViewBag.Invoices)
{
<tr>
<td>#_invoice.InvoiceId</td>
<td>#_invoice.Date</td>
<td>#_invoice.RecpDate</td>
<td>#_invoice.Category</td>
<td>#_invoice.TotalValue</td>
<td>#_invoice.InvoiceRef</td>
<td>#_invoice.Client</td>
<td>#_invoice.Status</td>
</tr>
}
}
</tbody>
</table>
And i can get the information from a row when its selected using javascript as follows:
// Row data
$(document).ready(function () {
oTable = $('#invoiceTable').dataTable();
oTable.$('tr').click(function () {
var data = oTable.fnGetData(this);
alert(data);
// ... do something with the array / object of data for the row
});
});
The variable data will provide a string of every value in the row separated by a comma as follows:
"000,26-01-14,27-01-14,001,1000,inv,something ltd,paid"
I want to have all these values separated. Note this could be done by splitting on the comma however a value in the table could contain commas.
How can I separate this string?
According to the DataTables documentation oTable.fnGetData(this); return an array filled with the data of the definitions in the row so you should be able to acces the data directly from data.
var invoiceId = data[0];
var date = data[1];
var recpDate = data[2];
// etc. etc.

JQuery tablesorter appended data not sorting

Im trying too append data to a table with the tablesorter plugin (http://tablesorter.com)
Im using the following code:
<table id="sortme" border="1" style="width: 200px;">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td>will</td>
<td>smith</td>
<td>1</td>
</tr>
...................
</tbody>
</table>
Click me!
And:
$(document).ready(function() {
var i = 5;
$("#sortme").tablesorter({
sortList: [[2,0]]
});
$("#test").click(function() {
$("#sortme tbody").append('<tr><td>NEW</td><td>NEW</td><td>'+(i++)+'</td></tr>');
$("#sortme").trigger("update");
var s = [[2,0]];
$("#sortme").trigger("sorton",[s]);
return false;
});
});
Problem is the appended row stays at top, why?
See example: http://jsfiddle.net/jmU3Z/8/
In case anyone else stumbles across this.
By the time the "sorton" event is handled the DOM hasn't been assigned the table.config.parsers. The "sorton" event handling needs to be wrapped in a 1 millisecond timeout.
Replace the existing "sorton" bind in jquery.tablesorter.js (line ~803) with the following:
}).bind("sorton", function (e, list) {
var me = this;
setTimeout(function () {
$(this).trigger("sortStart");
config.sortList = list;
// update and store the sortlist
var sortList = config.sortList;
// update header count index
updateHeaderSortCount(me, sortList);
// set css for headers
setHeadersCss(me, $headers, sortList, sortCSS);
// sort the table and append it to the dom
appendToTable(me, multisort(me, sortList, cache));
}, 1);
You're problem is the [s]. You're sort parameter is already an array, just pass it the var not the var in an array.
$("#sortme").trigger("sorton",s);
Works for me, FF4.

Categories

Resources