jQuery datatable fnDraw(false) not working - javascript

I am using DataTables 1.10.16 version.After updating the value i am refreshing the table with updated value.The only problem is its not keeping the pagination state.
example:- Suppose i am in page 2 and after updating the value it updates the value but taking me to first page.
I have tried fnDraw(false) but that is not working.
Initialise data table
$('.report-table').dataTable({
bInfo: false,
bLengthChange: false,
serverside: true,
stateSave: true,
dom: '<"top"i>rt<"bottom"lp><"clear">',
columnDefs: [{
"orderable": false,
"targets": 9
},
{
"className": "text-center",
"targets": 9
}
],
language: {
oPaginate: {
sNext: '<i class="fa fa-forward"></i>',
sPrevious: '<i class="fa fa-backward"></i>',
sFirst: '<i class="fa fa-step-backward"></i>',
sLast: '<i class="fa fa-step-forward"></i>'
},
emptyTable: "No application found"
},
serverMethod: 'get',
ajax: {
url: 'https://www.googl.com',
data: {
startDate: startDate,
endDate: endDate,
},
headers: {
'X-CSRF-TOKEN': "{{csrf_token()}}"
}
},
createdRow: function(row, data, dataIndex) {
$(row).attr('data-app-id', data.app_id);
},
columns: [{
"data": "app_id",
render: function(data) {
var firstColumn = data + '<i class="app-expand-btn fa fa-plus-circle pull-right" aria-hidden="true"></i>'
return firstColumn;
}
},
{
"data": "app_name"
},
{
"data": "ad_requests"
},
{
"data": "impressions"
},
{
"data": "fill_rate"
},
{
"data": "clicks"
},
{
"data": "ctr"
},
{
"data": "ecpm"
},
{
"data": "revenue"
},
{
"data": "app_id",
render: function(data) {
var lastColumn = '<div class="action-box-tools">\n' +
'<a class="application-edit-btn" data-placement="top" data-toggle="tooltip-custom" data-tooltip-value="Edit"><i class="fa fa-pencil"></i> </a>' +
'<a class="application-status-btn" data-placement="top" data-toggle="tooltip-custom" data-tooltip-value="Activate application"><i class="fa fa-play"></i></a>' +
'</div>'
return lastColumn
}
},
]
});
Refresh table
$.getJSON("{{url('https: //www.xyz.com')}}", params, function(json) {
oSettings = $('.report-table').dataTable().fnSettings();
$('.report-table').dataTable().fnClearTable(this);
for (var i = 0; i < json.data.length; i++) {
$('.report-table').dataTable().oApi._fnAddData(oSettings, json.data[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
$('.report-table').dataTable().fnDraw(false);
});

you can achieve this by ajax,
draw is basically a reset function,
there are work around with draw which you can found on internet
I normally use the following with serverside:true, processing:true, statesave:true
mytable.ajax.reload(null, false);
also change
dataTable
to
DataTable
. because dataTable is jquery obj and DataTable is datatable instance
you should use id instead of class to avoid any issue,
var mytable = $('.report-table').dataTable({
bInfo: false,
bLengthChange: false,
serverside: true,
stateSave: true,
processing: true, // also add this
. . .
and this will work anywhere, unless you have defined datatable in some function.
for example followincode will reload table on click of btn
$('#btn').click(function(){
mytable.ajax.reload(null, false);
});
reference to ajax.reload

Related

Datatables.net MVC JavaScript Populated table erroneously shows Showing 0 to 0 of 0 entries

First time using DataTables.net with MVC and JavaScript. On my .cshtml page I have a Datatables.net table that correctly brings back data and populates the table using JavaScript. (I have copied this from another example that also brings back data correctly and populates the table.) My problem is that at the bottom of the table it erroneously shows Showing 0 to 0 of 0 entries despite displaying multiple rows of information. (on the example that I copied from it correctly shows 1 of 20 entries).
My code below:
<script type="text/javascript">
function getTransactionListingHistory(contactCode) {
var groupColumn = 1;
if ($.fn.dataTable.isDataTable('#datatableTransactionHistory')) {
table = $('#datatableTransactionHistory').DataTable();
table.destroy();
}
var historyTable = $('#datatableTransactionHistory').DataTable({
order: [0, "desc"],
"processing": true,
"serverSide": true,
"filter": false,
"ajax": {
"url": "/Transactions/TransactionsGetData?contactCode=" + contactCode,
"type": "POST",
"datatype": "json"
},
columnDefs: [
//{ "targets": [1], "visible": false, "searchable": false }
],
"columns": [
{
"data": "lineDate", "name": "LineDate", "autoWidth": true,
},
{
"data": "lineReference", "name": "lineReference", "autoWidth": true,
"render": function(data, type, row) {
return data;
}
},
{
"data": "formattedDebitAmount", "autoWidth": true, "defaultContent": "",
"render": function(data, type, row) {
if (data != null) {
return "<a class='text-danger text-right text-nowrap'>" + data + "</a>";
}
}
},
{
"data": "LineID", "name": "lineID", "autoWidth": true,
"render": function(data, type, row)
{
return '<a onclick="repeatTransaction(' + '\'' + row.lineID + '\');" href="#" id="repeat-link"><img src="' + "/images/icons/refresh.svg" + '" /> ' + 'Repeat' + '</a>';
}
},
],
fixedHeader: true,
"aLengthMenu": [[10, 25, 50, 100, 250, 500], [10, 25, 50, 100, 250, 500]],
"iDisplayLength": #myPagingSize,
language: {
processing: "<div style='color: #ff6611!important;' class='spinner-border text-warning m-2' role='status' aria-hidden='true'></div> Processing ...",
paginate: {
next: '<i class="fas fa-arrow-right"></i>',
previous: '<i class="fas fa-arrow-left"></i>'
}
}
});
$('#datatableTransactionHistoryul.pagination').addClass("pagination-rounded");
};
</script>

Hide a button in jquery based on user access

I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.

How to manage datatable for large data

I have a datatable for report. When i tried to show my datas, My browser freezed or crashed. My js code on below
Reporting_Report.DTReport = $('#Report-ReportTable').DataTable({
"ajax": {
"url": "/Ajax/JsonProvider?Method=HardwareHostScreenUsage&GenericObject=true&Json=" + JSON.stringify(json),
"dataSrc": ""
},
"columns": [
{
"data": "BranchName",
"sTitle": "BranchName"
},
{
"data": "HardwareHostFriendlyName",
"sTitle": "Hardware Host Friendly Name"
},
{
"data": "HardwareHostScreenUsageScreenState",
"defaultContent": "N/A",
"sTitle": "Hardware Host Screen Name"
"render": function(data, type, full) {
if (data && Util.Check.IsInteger(data)) {
if (data == 1) {
return "Sorry Screen";
} else if (data == 2) {
return "Welcome Screen";
} else if (data == 3) {
return "Progress Screen";
}
}
}
},
{
"data": "HardwareHostScreenUsageSecondOnScreen",
"sTitle": "Elapsed Time On Hardware Host Screen"
},
{
"data": "HardwareHostScreenUsageRecordDate",
"sTitle": "Hardware Host Screen Usage Record Date"
"render": function (data, type, full) {
return Util.JsonDateToDate(data).format("dd.mm.yyyy HH:MM:ss");
}
}
],
"pageLength": 20,
"lengthMenu": [
[20, 50, 100, -1],
[20, 50, 100, "All"]
],
"info": false,
bFilter: true,
bInfo: false,
"order": [[0, "asc"]],
"scrollX": true,
dom: 'Bfrtip',
buttons: [
{
extend: 'copy'
},
{
extend: 'csv'
},
{
extend: 'excel'
},
{
extend: 'pdf',
title: "Detailed Ticket Report"
message: startDate + " " + startTime + " - " + endDate + " " + endTime + "\t" + datetime,
pageSize: 'LEGAL'
},
{
extend: 'print'
}
]
});
I have more than 100.000 datas.
I thinked maybe i can just get showing page datas and total data number(for manage page numbers) and when clicked another page number send new query and get new datas. But i couldn't find how to do that to.(maybe it cause some another problems (shorting, searching vs.)
Have you got any ideas and solutions.(or this problem has already a solution)
footnote:json has some filters for query(time, branch, etc.)
HardwareHostScreenUsage method gets my datas on c# side.
you can use client side data source also-
var mydata = [];
$('#example').DataTable({
data: data,
deferRender: true,
scrollY: 200,
scrollCollapse: true,
scroller: true
});
fetch all data at once from server and show it while scrolling the table .
You Need these library -
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/scroller/1.4.3/js/dataTables.scroller.min.js

Jquery Datatables Selected Checkbox to Input Field

I have here a Datatable with 3 columns: Checkbox, Name, and SSNTIN, when I select rows then click Submit, their SSNTIN will output in '#txtSSNTIN' input field like "1001,1002,1003" but my problem is only the selected rows in the current page of my Datatable are being outputted in the input field, when I go to another page there is an indicator that the other rows from the previous page are still selected but only current page is outputting, please help
Datatable
Namestable = $('#NamesDatatable').DataTable({
'select': {
'style': 'multi',
},
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'render': function (data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="'+data.ssn_or_tin+'">';
}
}],
'order': [[1, 'asc']],
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
data: null,
defaultContent: '',
},
{ "data": "name", "autoWidth": true },
{ "data": "ssn_or_tin", "autoWidth": true }
]
});
Submit Button
$('#btnSubmit').on("click", function (e) {
e.preventDefault();
var searchNames = $('input:checkbox:checked').map(function () {
return $(this).val();
}).get();
$('#txtSSNTIN').val(searchNames);
});

Datatables - Refresh/Reload ajax not working

Hi folks I was able to sucessfully create a datatable that would get it's data from an ajax call. So for the initial loading is working fine. I created a button called refresh and I was hoping that if I call my function initiatearchiveIncidents it would go and fetch my data again and reload the table but instead im getting the error cannot re-initialise the Datatable.
So I tried doing dtTable.ajax.reload(); but this fails because it dosent understand my ajax call. Would anyone know how to do this properly?
initiatearchiveIncidents: function () {
$.getJSON(this.basePath() + '/XPROD_Incidents?$filter=ÉtatValue%20eq%20%27Fermé%27&$orderby=Modifié asc',
function (data) {
//Sharepoint REST returns a nested data format, so we go deep to get the useful parts
var myData = data.d.results;
moment.locale('fr');
//this is the key part of datatables
dtTable = $('#example').DataTable({
data: myData,
columns:[
{
"width": "30px",
sortable: false,
"render": function (data, type, full, meta) {
return "<button class='edit_button btn btn-default btn-sm' name ='btnSubmit' type='button' value='Edit' data-ID='"+full.ID+"'><i class='fa fa-pencil fa-2'></i></button>";
}
},
{ data: "Incident", "width": "75px" },
{
"width": "65px",
sortable: false,
"render": function (data, type, full, meta) {
return "<h4><span class='priorité_span'>"+full.PrioritéValue+ "</span></h4>";
}
},
{ data: "Composante","width": "75px",className: "over_flow_control" },
{ data: "Description","width": "300px",className: "over_flow_control" },
{ data: "Début_imputabilité","width": "100px" },
{ data: "ResponsableValue","width": "100px",className: "over_flow_control" }
],
"order": [[ 5, "desc" ]],
"drawCallback": function( settings ) {
IncidentManager.table_conditional_format();
$('#loading').hide("slow");
},
})
});
},
You need to rewrite your initiatearchiveIncidents() function to use jQuery DataTables Ajax functionality with ajax.url and ajax.dataSrc options, see below.
When you need to reload the data, just call $('#example').DataTable().ajax.reload(), see ajax.reload() for more details.
initiatearchiveIncidents: function() {
moment.locale('fr');
//this is the key part of datatables
dtTable = $('#example').DataTable({
ajax: {
url: this.basePath() + '/GDI_PROD_Incidents?$filter=ÉtatValue%20eq%20%27Fermé%27&$orderby=Modifié asc',
dataSrc: "d.results"
},
columns: [
{
"width": "30px",
sortable: false,
"render": function(data, type, full, meta) {
return "<button class='edit_button btn btn-default btn-sm' name ='btnSubmit' type='button' value='Edit' data-ID='" + full.ID + "'><i class='fa fa-pencil fa-2'></i></button>";
}
}, {
data: "Incident",
"width": "75px"
}, {
"width": "65px",
sortable: false,
"render": function(data, type, full, meta) {
return "<h4><span class='priorité_span'>" + full.PrioritéValue + "</span></h4>";
}
}, {
data: "Composante",
"width": "75px",
className: "over_flow_control"
}, {
data: "Description",
"width": "300px",
className: "over_flow_control"
}, {
data: "Début_imputabilité",
"width": "100px"
}, {
data: "ResponsableValue",
"width": "100px",
className: "over_flow_control"
}
],
"order": [[5, "desc"]],
"drawCallback": function(settings) {
IncidentManager.table_conditional_format();
$('#loading').hide("slow");
}
});
},

Categories