Datatable doesn't load JSON data, shows message "No data available in table" - javascript

I'm using Datatables.net to display data on my Shopify site. As an example, I just set the JSON data to have 1 key value pair of "itemcode" and then the actual product's item code. Here is an example of my data:
JSON Data
{
"jsonData": [
{
"itemcode": "0735340080 - Bearings"
},
{
"itemcode": "BL208-Z - Bearings"
},
{
"itemcode": "9109K - Bearings"
},
{
"itemcode": "735330016 - Bearings"
},
{
"itemcode": "699-ZZ - Bearings"
},
{
"itemcode": "698-ZZ - Bearings"
},
{
"itemcode": "697-ZZ - Bearings"
}
]
}
I'm using this code to load the data in. To clarify, the JSON is loaded from a hidden div element on the page:
Javascript Code
$(document).ready(function () {
var jsonDataDiv = document.getElementById("json-data").innerText;
var jsonData = JSON.parse(jsonDataDiv);
var table = $('#tableAppend').DataTable({
orderCellsTop: true,
pageLength: 25,
data: jsonData,
"columns": [{jsonData: "itemcode"}],
columnDefs: [
{"className": "dt-center", "targets": "_all"}
],
});
});
No errors are reported in the debug window, but my table states that no data was available. My HTML code is here:
HTML Code
<table class="display" id="tableAppend" style="margin-left: 20px;margin-right: 20px;">
<thead>
<tr>
<th class="dt-center">Item Code</th>
</tr>
</thead>
</table>
I've been following Q&A's online, but they don't seem to relate to my problem.

The issue is in the initialization of the table
Check out https://codepen.io/mvinayakam/pen/abzpJar
$(document).ready(function () {
var jsonDataDiv = document.getElementById("json-data").innerText;
var jsonData = JSON.parse(jsonDataDiv);
var table = $('#tableAppend').DataTable({
orderCellsTop: true,
pageLength: 25,
data: jsonData,
"columns": [{data: "itemcode"}],
columnDefs: [
{"className": "dt-center", "targets": "_all"}
],
});
})
As an aside, I am assuming the json is in the div only for trial purposes.

You have to only change the data table column assign parameter name jsonData --> data
"columns": [{data: "itemcode"}],

Related

JQuery DataTable Page Length Not Being Honored After Page 1

I have a JQuery data table that has a large amount of data. I set the page length, but whenever I go past the first page, it does not honor the the length anymore.
As you can see, the page length is 50 which honored on the first page, but after that, the length is no longer honored.
This is my script:
dataTable = $("#sampleTable").DataTable({
"ajax": {
"url": '....',
"contentType": "application/json",
"type": "POST",
"dataSrc": ""
},
"columns": [
{"data": "name", "title": "Name"},
{"data": "value", "title": "Value"}
],
"order": [[1, 'desc']],
"createdRow": function(tr, _, rowIndex) {
return $(tr).attr('rowindex', rowIndex)
},
"bDestroy": true,
"pageLength": 50,
"lengthMenu": [ 10, 15, 20 , 30, 50],
});
The version I am using is jquery 1.21.1 and datatables 1.10.21
Update: As requested, this is what get's called by the ajax call
#PostMapping(value = Paths.SAMPLE, consumes = { MediaType.APPLICATION_JSON }, produces = {
MediaType.APPLICATION_JSON })
#ResponseBody
public Collection<SampleData> retrieveSamples() {
return sampleDBDao.retrieveData();
}
sample.tag
<table id="sampleTable" class="table" style="width: 100%">
</table>
Is the issue because there is a large amount of data?

append column data outside the datatable container

I am using JQuery datatable, after loading the data from server, my table looks something like this:
As you can see my table has six columns. The last column which is Contracted product, has the same data inside, I want to get the value and display it outside the datatable so it becomes more reader friendly as shown in picture 2.
My code looks like this:
var table = $('#products').DataTable( {
"processing": true,
"serverSide": true,
"paging": true,
"scrollX":"true",
"ordering": [],
"stateSave": false,
"info": true,
"dom": 'lrtip',
"ajax":
{
url:"xxxxxx_fetch.php",
type:'POST'
},
"columns": [
{ data: "product_code_fk" },
{ data: "product_name" },
{ data: "start_date" },
{ data: "end_date" },
{ data: "pack_size" },
{ data: "contract_prod" }
],
} );
Through the use of the header and footer callback manipulation functions provided by DataTables (headerCallback and footerCallback).
in HTML, by exemple
<tfoot>
<tr>
<th colspan="4" style="text-align:right">CONTRAT PROD :</th>
<th></th>
</tr>
</tfoot>
DataTable
$('#example').DataTable( {
"footerCallback": function ( row, data, start, end, display ) {
let api = this.api(), data;
...
$( api.column( 4 ).footer() ).html(
your_DATA
);

Reload dataTable from variable

I searched all over web and I didn't find easy solution for this. I'm using jQuery DataTables with "static" data source (one var is filled with data using SignalR and then later, DataTable is built). Now, when change of this dataset comes, I want to update table using this data set. Ideally, that would be simple "refresh" which reloads data from specified source. Here is my HTML
<table class="table table-hover table-condensed table-responsive" id="tableAccounts">
<thead>
<tr>
<th data-localize="_A_C">_A_C</th>
<th data-localize="_Name">_Name</th>
<th data-localize="_Address">_Address</th>
<th data-localize="_City">_City</th>
<th data-localize="_Phone">_Phone</th>
</tr>
</thead>
<tbody></tbody>
And here is my javascript which initially loads data:
tAccounts = $('#tableAccounts').dataTable({
"data": AccountAll,
"bFilter": true,
"pageLength": 100,
"bSearchable": true,
"bInfo": false,
"columns": [
{ "data": "AccountCode" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "Phone" }
],
"columnDefs": [
{
"render": function (data, type, row) {
return ("0000" + data.toString(16)).slice(-4);
},
"targets": 0
},
{ "visible": true, "targets": [0] }
]
});
tl;dr;
How to refresh datatable when data source (AccountAll in this case) is changed without destroying whole table? Bonus point if selection and filter is preserved.
Change can be anything. New row added, row removed, cell value changed.
You can use combination of clear() and rows.add() API methods to clear existing data and add updated data.
In this case filtering and sorting would be preserved.
If you want to preserver the current page, call draw(false) instead of draw() but if you're adding new rows, there is little sense in preserving the current page
For example:
var data = [['old',2,3,4,5,6]];
var table = $('#example').DataTable({
'data': data
});
var dataNew = [['new',2,3,4,5,6]];
table.clear().rows.add(dataNew).draw();
See this example fro code and demonstration.

Error while refreshing datatables - Cannot reinitialise DataTable

I have a json data that contains 2 arrays with multiple objects and I have put together the following code that enables me to make only one call and split the results into 2 tables. The issue I am having now is I can't refresh the tables anymore. I have tried different options but getting Cannot reinitialise DataTable which makes sense, so i guess I am stuck right now.
Code:
$(document).ready(function (){
setInterval (function(){
$.getJSON("ajax/json.txt", function (pcheckdata){
<!-- ------------------- Extract Only Alerts ---------------------- -->
$('#alert-table').dataTable({
"bJQueryUI": true,
"data": pcheckdata.alerts,
"columns": [
{ "mData": "host" },
{ "mData": "description" }
],
});
<!-- ------------------- Extract Only Errors ---------------------- -->
$('#error-table').dataTable({
"bJQueryUI": true,
"data": pcheckdata.errors,
"columns": [
{ data: 'host' },
{ data: 'description' }
],
});
});
}, 1000);
});
My JSON Structure
{
"alerts": [
{
"host": "server1",
"description": "Engine Alive"
},
{
"host": "ftpserver",
"description": "Low free disk space"
}
],
"errors": [
{
"host": "server3",
"description": "Can't connect to MySQL server"
},
{
"host": "server4",
"description": "SSQL timeout expired"
}
]
}
HTML Bit:
<table id="alert-table" class="display" cellspacing="0">
<thead class="t-headers">
<tr>
<th>HOST</th>
<th>DESCRIPTION</th>
</tr>
</thead>
</table>
<table id="error-table" class="display" cellspacing="0">
<thead class="t-headers">
<tr>
<th>HOST</th>
<th>ERROR DESCRIPTION</th>
</tr>
</thead>
</table>
I would love to know if there is a way to refresh the 2 tables at the same time since the data will only be fetched once or is it better to use purely JQUERY and forget about datatables as it seems to be giving me headache
Why do you want to reinit whole table, just create table once and on ajax callback, clear the table and add the data. Which version of datatable are you using? I used the old function to clear and add data, with new table it will differ but you know the idea.
Here is an example:
$(document).ready(function (){
//Init datatables without data
<!-- ------------------- Extract Only Alerts ---------------------- -->
var alertTable = $('#alert-table').dataTable({
"bJQueryUI": true,
"columns": [
{ "mData": "host" },
{ "mData": "description" }
],
});
<!-- ------------------- Extract Only Errors ---------------------- -->
var errorTable = $('#error-table').dataTable({
"bJQueryUI": true,
"columns": [
{ data: 'host' },
{ data: 'description' }
],
});
setInterval (function(){
$.getJSON("ajax/json.txt", function (pcheckdata){
alertTable.fnClearTable(); //New API then alertTable.clear().draw();
alertTable.fnAddData(pcheckdata.alerts); //New API then alertTable.row.add(pcheckdata.alerts);
alertTable.fnAdjustColumnSizing(); //New API then alertTable.columns.adjust().draw();
errorTable.fnClearTable(); //New API then errorTable.clear().draw();
errorTable.fnAddData(pcheckdata.errors); //New API then errorTable.row.add(pcheckdata.errors);
errorTable.fnAdjustColumnSizing();////New API then errorTable.columns.adjust().draw()
});
}, 1000);
});
Another way is check if datatables are already init.
$(document).ready(function (){
setInterval (function(){
$.getJSON("ajax/json.txt", function (pcheckdata){
//Is datatable already init.
if ( ! $.fn.DataTable.isDataTable( '#alert-table' ) ) {
<!-- ------------------- Extract Only Alerts ---------------------- -->
$('#alert-table').dataTable({
"bJQueryUI": true,
"data": pcheckdata.alerts,
"columns": [
{ "mData": "host" },
{ "mData": "description" }
],
});
}else
{
$('#alert-table').dataTable().clear().draw();
$('#alert-table').dataTable().row.add(pcheckdata.alerts);
$('#alert-table').dataTable().columns.adjust().draw();
}
if ( ! $.fn.DataTable.isDataTable( '#error-table' ) ) {
<!-- ------------------- Extract Only Errors ---------------------- -->
$('#error-table').dataTable({
"bJQueryUI": true,
"data": pcheckdata.errors,
"columns": [
{ data: 'host' },
{ data: 'description' }
],
});
}else
{
$('#error-table').dataTable().clear().draw();
$('#error-table').dataTable().row.add(pcheckdata.errors);
$('#error-table').dataTable().columns.adjust().draw();
}
});
}, 1000);
});

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources