angular / Jquery Cannot reinitialise DataTable - javascript

I'm working on angular project and I'm sorting my data into a datatable, it's initialized in a js file like that :
$(function () {
$('#sorting-table').DataTable({
"language": {
"lengthMenu": "Afficher _MENU_ par page",
"zeroRecords": "Nothing found - sorry",
"info": "Page _PAGE_ de _PAGES_",
"infoEmpty": "Aucun résultat trouvé",
"zeroRecords": "Rien trouvé - Désolé",
"search": "Chercher",
"infoFiltered": "(total: _MAX_ )",
"paginate": {
"previous": "Précédent",
"next": "Suivant"
}
},
"lengthMenu": [
[5, 10, 15, -1],
[5, 10, 15, "Tous"]
],
"order": [
[0, "desc"]
],
dom: 'lBfrtip',
buttons: {
buttons: [{
attr: { id: 'printButton' },
extend: 'print',
text: '<i class="la la-print"></i>',
title: $('h1').text(),
exportOptions: {
columns: [ 0, 1, 2, 3]
},
footer: true,
autoPrint: true,
}],
dom: {
container: {
className: 'dt-buttons'
},
button: {
className: ''
}
}
}
});
});
})(jQuery);
On a component that my table is sorted I want to work with angular ngx-translation, if the current language change I want to change the language of my data table !
ngOnInit() {
this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
if (this.translate.currentLang === 'ar') {
$('#sorting-table').DataTable({
language: {
url: 'cdn.datatables.net/plug-ins/1.10.20/i18n/Arabic.json'
}
});
}
})
}
I got this error :
DataTables warning: table id=sorting-table - Cannot reinitialise
DataTable. For more information about this error, please see
http://datatables.net/tn/3

url should be like this : //cdn.datatables.net/plug-ins/1.10.20
and add destroy:true

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>

PDF does not show complete with datatable button

I'm trying to visualize the pdf of almost all the datatable's columns, however, the pdf document does not show the last two columns. Having said that, I have two questions. First how can I make the column "Opciones" not to appear, and the second is, how can I make the pdf to show complete? I would appreciate any help. Thanks
This is my code:
function listar() {
tabla = $('#tbllistado').dataTable({
"aProcessing": true,//activamos el procedimiento del datatable
"aServerSide": true,//paginacion y filrado realizados por el server
dom: 'Bfrtip',//definimos los elementos del control de la tabla
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdf'
],
"ajax":
{
url: '../ajax/venta.php?op=listar',
type: "get",
dataType: "json",
error: function (e) {
console.log(e.responseText);
}
},
"bDestroy": true,
"iDisplayLength": 5,//paginacion
"order": [[0, "desc"]]//ordenar (columna, orden)
}).DataTable();
}
and the images of the results
enter image description here
And also this is the pdf
enter image description here
I figure it out by myself, all I had to do was to add some parameters to the pdf button. Thank you so much
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
{
extend: 'pdf',
orientation: 'landscape',
exportOptions: {
columns: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
}
}
]

How can I decode JSON Unicode using jQuery in a Select2 dropdown filter

I am using Select2 JS and Datatables JS. The data is in JSON format. The data for one value should display as Animal & Veterinary. In JSON it appears as Animal \u0026amp; Veterinary. The Select2 filter displays it as Animal & Veterinary. How can I add a function to the JS below that will decode the Unicode? Below is a function that can work but I dont know how to add it to the JS below.
var title = 'Animal & Veterinary';
function stringToSlug (title) {
return title.toLowerCase().trim()
.replace(/&/g, 'and')
}
Below is the script. This is where I would like to pass the function into the filter. "select2config"
jQuery( document ).ready( function($) {
'use strict';
// Check condition first if the table class exists then run this init.
if ($('.lcds-datatable--advisory-committee-materials').length > 0) {
let pageClass = function () {
let el = $( 'ul.pagination' ).addClass('pagination-sm');
}
// define order of table's control element
let domStyling = "<'row'<'col-sm-12'lB>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>";
var otable9 = $('table.lcds-datatable--advisory-committee-materials').DataTable( {
// Sort of first date column descending.
order: [[0, 'desc']],
deferRender: true,
deferLoading: 50,
dom: domStyling,
ajax: {
"url": "/datatables-json/advisory-committee-materials-json",
//"url": "/sites/default/files/actest1.json",
"dataSrc": ""
},
processing: true,
columns: [
{ "data": "field_publish_date" }, // publish_date 0
{ "data": "title" }, // node title summary 1
{ "data": "field_site_structure" } // site_structure Committee/Topic 2
],
columnDefs: [
{
"type": "date",
"targets": [ 0 ]
}
],
pageLength: 10,
searching: true,
autoWidth: false,
responsive: true,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
buttons: [
{
extend: 'excel',
text: 'Export Excel',
exportOptions: {
columns: [ 0, 1, 2 ]
}
}
],
initComplete: pageClass,
drawCallback: pageClass
}); // end datatable
// config and initialize filters
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
}
let search = $( '#lcds-datatable-filter--search' ).lcdsTableFilter({
table: otable9,
type: 'search'
});
let clear = $( '#lcds-datatable-filter--clear' ).lcdsTableFilter({
table: otable9,
type: 'clear'
});
// wait for ajax call to complete to load column data load
$('table.lcds-datatable--advisory-committee-materials').on( 'init.dt', function() {
let committee = $( '#lcds-datatable-filter--committee-topic' ).lcdsTableFilter({
column: 2,
table: otable9,
select2Options: select2config,
type: 'select',
dataType: 'datatable'
});
})
}}); // end ready function and condition if the table class exists.
I was able to pass in a function to alter the output of JSON so now the filter displays “Animal & Veterinary” not “Animal & Veterinary” By adding this below. The filter now displays Animal & Veterinary but selecting this in the filter does not match the value in the datatable?
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
escapeMarkup: function (text) { return text; }
}

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 - Show Last Page First

I am using the jQuery DataTables plugin (https://datatables.net/). I am trying to get the last page to be the first page. I am sorting by date and would like the latest entries to be at the bottom of the visible area.
So if the "Records per page:" is 10, then the latest date should be at the bottom. I am using the plugin to create a "logbook" so the latest entries should always be at the bottom. I have tried the following but I can't get it to work:
jQuery
// On page load: datatable
var table_companies = $('#table_companies').dataTable({
"ajax": "data.php?job=get_companies",
"sDom": '<"top"lB><"clear">rt<"bottom"p><"clear">',
"language": {
"paginate": {
"previous": "Older Entries"
}
},
"autoWidth": false,
"searching": true,
"columns": [
{ "data": "date" },
{ "data": "type", "sClass": "company_name" },
{ "data": "registration" }
],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [-1] }
],
"lengthMenu": [[5, 10, 25, 50, 100], [5, 10, 25, 50, 100]],
"pagingType": "simple",
"oLanguage": {
"sLengthMenu": "Records per page: _MENU_",
"sInfo": "Total of _TOTAL_ records (showing _START_ to _END_)",
"sInfoFiltered": "(filtered from _MAX_ total records)"
}
});
table_companies.fnPageChange( 'last' );
I am using this link to load my plugin:
<script type="text/javascript" src="https://cdn.datatables.net/t/dt/dt-1.10.11,b-1.1.2,b-colvis-1.1.2,b-print-1.1.2,cr-1.3.1,r-2.0.2/datatables.min.js"></script>
Please check this code:
$('#datatable').DataTable().page('last').draw('page');
It turns out it was as simple as capitalizing the "D" in dataTables.
Changed:
var table_companies = $('#table_companies').dataTable({
to:
var table_companies = $('#table_companies').DataTable({

Categories