How to deal with null values in JQuery DataTable when using ajax - javascript

I'm getting the following error when my page tries to load a DataTable:
DataTables warning: table id=table1 - Requested unknown parameter '0'
for row 0, column 0. For more information about this error, please see
http://datatables.net/tn/4
The table loading works fine when I use a dummy data set of random values, but the data I would like to display has many null values, and this may be why the problem arises. I would like to know how best to set the DataTable settings such that null values are recognized and displayed as an empty string.
I tried adding a render function to solve the issue (adapted from an example described in the comments on datatables oficial forum), but it's not currently working, and I'm not sure how best to implement it, or if it would be better to use another method altogether.
jQuery:
function setupData() {
$(document).ready(function () {
$('#table1').dataTable({
"dom": 'B<clear>frtip',
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"scrollX": true,
"scrollY": true,
"ajax": {
"url": "/index_get_data",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
responsive: true
});
});
}
$(window).on("load", setupData);
html:
<table contenteditable='true' id="table1" class="tableBody dataTable table-striped table-bordered nowrap display" style="width:100%" >
<thead>
<tr>
{% for item in cols %}
<th>{{ item }}</th>
{% endfor %}
</tr>
</thead>
</table>
A render function that I added to the dataTable declaration, but I couldn't get this to work:
"render": function jsRenderCOL(data, type, row, meta) {
var dataRender;
if (data == null) {
dataRender = "";
}
return dataRender;
}
There are over 130 columns (this can be variable), and the data is updated daily, with many columns potentially containing null data. I'd like to find a method to display the data within the dataTable where the columns don't have to be declared explicitly within the dataTable function. Thanks for any help you can provide.

You could try to set the defaultContent on initialisation for each and every column to be an empty string i.e.
$('#table1').dataTable( {
"columnDefs": [ {
"targets": (pass a variable in here that you have calculated based on the number of columns to render)
"defaultContent": ""
} ]
} );
and for the targets attribute pass in a variable that defines the indexes of the columns.

You dont have to worry about ajax data use this code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data':{}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});

Add
columnDefs:[
{"render":function(data){if(data == "null") {return "-"} else {return data}}, "targets":"_all" },
],

Related

DataTables warning: table id=escritorios - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

I have these two codes and one cancels the other. I need help getting the two together. Thanks
<script type="text/javascript" class="init">
$(document).ready(function() {
var table = $('#escritorios').DataTable({
lengthChange: false,
buttons: ['colvis', 'print', 'copy', 'excel', 'pdf']
});
table.buttons().container().appendTo('#example_wrapper .col-md-6:eq(0)');
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#escritorios').DataTable({
responsive: {
details: {
type: 'column',
target: 'tr'
}
},
columnDefs: [{
className: 'control',
orderable: false,
targets: 0
}],
order: [1, 'asc']
});
});
</script>
Looks like you are trying to reinitialise a datatable with same ID. To reinitialise a datatabe you have to destroy it first.
if ($.fn.DataTable.isDataTable('#Table')) {
$('#Table').DataTable().destroy();
}
The issue is because you're initialising the DataTable() library on the same element multiple times, which is invalid, and causes the error you see.
To fix this combine all the settings in to a single call, like this:
jQuery(function($) {
var table = $('#escritorios').DataTable({
lengthChange: false,
buttons: ['colvis', 'print', 'copy', 'excel', 'pdf'],
responsive: {
details: {
type: 'column',
target: 'tr'
}
},
columnDefs: [{
className: 'control',
orderable: false,
targets: 0
}],
order: [1, 'asc']
});
table.buttons().container().appendTo('#example_wrapper .col-md-6:eq(0)');
});

How to format currency in Datatables?

This is a table which display transactions, implementes using DataTables.
$( document ).ready(function() {
var table = $('#tbl_transaksi').DataTable( {
"ajax": "data_transaksi.php",
"bPaginate":true,
"bProcessing": true,
"pageLength": 10,
"columns": [
{ mData: 'username' } ,
{ mData: 'fullname' },
{ mData: 'the_date' },
{ mData: 'amount', render: function ( data, type, row ) {
return "Rp " + data;
}
}
],
"dom": 'Bfrtip',
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
});
It works. Now I want to add an enhancement: format the amount ("jumlah") using Indonesian format, so for example 1000000 will be displayed as "Rp 1.000.000";
A Google search pointed me to renderers. I added the render part into my code, and well it doesn't change the formatting. What is wrong here?
use $.fn.dataTable.render.number function,
$( document ).ready(function() {
var table = $('#tbl_transaksi').DataTable( {
"ajax": "data_transaksi.php",
"bPaginate":true,
"bProcessing": true,
"pageLength": 10,
"columns": [
{ mData: 'username' } ,
{ mData: 'fullname' },
{ mData: 'the_date' },
{ mData: 'amount', render: $.fn.dataTable.render.number( ',', '.', 3, 'Rp' )
}
],
"dom": 'Bfrtip',
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
});
Hope this thing solve your problem.
$(document).ready(function () {
var table = $('#tbl_transaksi').DataTable({
"ajax": "data_transaksi.php",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [
{ mData: 'username' },
{ mData: 'fullname' },
{ mData: 'the_date' },
{
mData: 'amount', render: function (data, type, row, meta) {
return meta.settings.fnFormatNumber(row.amount);
}
}
],
"dom": 'Bfrtip',
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
});
use it gan :
{
mData: 'amount', render: $.fn.dataTable.render.number( '.', ',', 0, 'Rp ' )
}
//result Rp 175.000
in indonesian rupiah they use dot (.) for currency not comma

Print all data from datatable

I'am using asp.net mvc. when datatable list, send action and response only paging data. if click to print button, I want to all data print.
var table = $('#dataTableNoticeReport');
var oTable = table.dataTable({
"bScrollCollapse": true,
"bDestroy": true,
"paging": true,
"ordering": false,
"info": true,
"bFilter": true,
"bProcessing": true,
"bLengthChange": true,
"bServerSide": true,
"sAjaxSource": "/Manage/Notice/_NoticeDatatable?readStatus=" + $(this).val() + "&noticeId=" + $("#NoticeSearch_Id").val(),
"sServerMethod": "POST",
"aoColumns": [{
"mDataProp": "Name"
}, {
"mDataProp": "SurName"
}, {
"mDataProp": "PhoneNumber"
}, ],
// Internationalisation. For more info refer to http://datatables.net/manual/i18n
"language": {
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"emptyTable": "Tabloda Gösterilecek Kayıt Bulunamadı",
"info": "Gösterilen : _START_ - _END_ / _TOTAL_ ",
"infoEmpty": "Kayıt Bulunamadı.",
"infoFiltered": "(Toplam _MAX_ kayıttan sorgulama yapıldı.)",
"lengthMenu": "_MENU_ Kayıt Sayısı",
"search": "Ara:",
"zeroRecords": "Kayıt Bulunamadı."
},
// Or you can use remote translation file
//"language": {
// url: '//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Portuguese.json'
//},
dom: 'Bfrtip',
buttons: [{
extend: 'print',
"sButtonText": 'Export',
className: 'btn default',
oSelectorOpts: {
page: 'all'
},
bShowAll: true,
sAjaxSource: "/Manage/Notice/_NoticeDatatable?readStatus=" + $(this).val() + "&noticeId=" + $("#NoticeSearch_Id").val()
}, {
extend: 'copy',
className: 'btn default'
}, {
extend: 'pdf',
className: 'btn default'
}, {
extend: 'excel',
className: 'btn default'
}, {
extend: 'csv',
className: 'btn default'
},
],
"order": [
[0, 'asc']
],
"lengthMenu": [
[5, 10, 15, 20, 5000],
[5, 10, 15, 20, "All"] // change per page values here
],
// set the initial value
"pageLength": 10,
});
it's not working below code.
buttons: [{
extend: 'print',
"sButtonText": 'Export',
className: 'btn default',
oSelectorOpts: {
page: 'all'
},
bShowAll: true,
sAjaxSource: "/Manage/Notice/_NoticeDatatable?readStatus=" + $(this).val() + "&noticeId=" + $("#NoticeSearch_Id").val()
}, {
extend: 'copy',
className: 'btn default'
}, {
extend: 'pdf',
className: 'btn default'
}, {
extend: 'excel',
className: 'btn default'
}, {
extend: 'csv',
className: 'btn default'
},
],
When I was click to print button,return only 10 record but I want to all record print.
I am using the datatables serverside too and this is how I managed to print all data without braking anything: providing the "lengthMenu" option to let user select all data:
$('#table').DataTable({
"ajax": {
url: "my_url",
type: 'POST'
},
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"processing": true,
"serverSide": true,
"bPaginate": true,
"sPaginationType": "full_numbers",
"columns": [
{ "data": "a" },
{ "data": "b" },
{ "data": "c" },
{ "data": "d" },
{ "data": "e" }
],
"dom": 'Blfrtip',
"buttons": [
{
extend: 'print'
}
]
});
});
Here, with providing the "lengthMenu" option, the user can select a range or "All" data to view and if the user wants to export all data, then the user will select the "All" selection from the length menu drop down.
I think when server side is enabled, you need to return the number of records. See the documentation, especially the ajax section. Note the records total in the JSON response:
"recordsTotal": 57,
Here's a good Datatables support thread: https://datatables.net/forums/discussion/32031/pagination-with-server-side-processing. They discuss server side pagination in detail.

Incorrect header when exporting to PDF with yadcf filter

When I am trying to export to pdf my Datatable with a filter yadcf, the header show always every case from my filter, how can I hide that?
My javascript is :
var vsan = $('#vsan').DataTable( {
"lengthMenu": [ [-1, 10, 40, 50], ["All", 10, 40, 50] ],
"sDom": '<"top"i>fBltif',
"buttons": [
{
extend: 'print',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excel',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdfHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'copyHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csv',
exportOptions: {
columns: ':visible'
}
}
],
"bJQueryUI": true, //Enable jQuery UI ThemeRoller support
"bAutoWidth": false,
"bDestroy": true,
//"order": [[ 3, "desc" ]], //tri par défaut
"bStateSave": false, //plante ?
"bPaginate": true, //Enable or disable pagination.
"bInfo": true,
});
yadcf.init(vsan, [{column_number : 0, filter_type : "none"}, {column_number : 1, filter_type : "none"}, {column_number : 2, filter_type : "none"}, {column_number : 3, filter_type : "select"}, {column_number : 4, filter_type : "auto_complete"}, {column_number : 5, filter_type : "range_number_slider"},{column_number : 6, filter_type : "none"}, {column_number : 7, filter_type : "range_number_slider"}]);
Here is the problem :
i'm using :
http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js
https://rawgit.com/vedmack/yadcf/8e071af195106fa702f942373c65164b89ca40ff/jquery.dataTables.yadcf.js
Thanks
Ok i did it, but i think it s very weird :
exportOptions: {
columns: ':visible' ,
format: {
header: function ( data, column, row )
{
return data.substring(data.indexOf("inline-block")+15,data.indexOf("<span"));
}
}
}
I don't know if is it to me to patch that, or maybe there is a bug, but the point is that it works !
I too faced this issue and I did something like below:-
exportOptions: {
columns: ':visible' ,
format: {
header: function ( data, column, row )
{
return data.split('<')[0];
}
}
}
It worked for me. This will remove the div which is getting added.
When I checked my header data was something like: -
column name<div id="yadcf-filter-wrapper--crime_table-7" class="yadcf-filter-wrapper"><select id="yadcf-filter--crime_table-7" class="yadcf-filter " onchange="yadcf.doFilter(this, '-crime_table', 7, 'contains');" onkeydown="yadcf.preventDefaultForEnter(event);" onmousedown="yadcf.stopPropagation(event);" onclick="yadcf.stopPropagation(event);"><option value="-1">Select Column</option>............................<button type="button" id="yadcf-filter--crime_table-7-reset" onmousedown="yadcf.stopPropagation(event);
So I split the div from the column name and kept just the header.

Datatables using JSON

I have been stuck for days on this issue. I am trying to pull data into my datatable for an inventory system using JSON data. I for some reason cannot get my In Inventory column to display the number of items left. The data is being pulled from my JSON file located at http://lungavitadesigns.com/api/inventory_list.php
The datatable is located at http://lungavitadesigns.com/inventory.php
Below is the code I am using to populate the data. Any help is highly appreciated.
$(document).ready(function() {
$('#inventory').DataTable( {
columnDefs: [
{
targets: [ 0, 1, 2 ,3,4]
}
],
"scrollY": "700px",
"scrollCollapse": true,
"paging": false,
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"ajax": 'http://lungavitadesigns.com/api/inventory_list.php',
"columns": [
{
"data": "master_image.url",
"render": function ( data, type, full, meta ) {
return '<img src="'+data+'" width="100px" height="100px" />';
}
},
{"data": "name"},
{
data: 'variations.0.price_money.amount',
render: function ( data, type, row ) {
return '$'+ data;
}
},
{data: "inventory.quantity_on_hand"},
{"data": "available_online"}
],
});
} );
Your JSON response is missing inventory and inventory.quantity_on_hand properties for each row.

Categories

Resources