Error while refreshing datatables - Cannot reinitialise DataTable - javascript

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);
});

Related

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

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"}],

datatable warning 4 - Requested unknown parameter '0' for row 0, column 0

I am working on datatable and facing this error :
DataTables warning: table id=table - Requested unknown parameter '0'
for row 0, column 0.
I have studied this link and it says that my table column defines in HTML doesn't match with the columns received from server. BUT in my case both are same.
Here is my HTML code :
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;">
<tr>
<th>aNumber</th>
<th>bNumber</th>
<th>cellID</th>
<th>dateTime</th>
<th>duration</th>
<th>imei</th>
<th>imsi</th>
<th>operatorId</th>
<th>mscId</th>
<th>fileId</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Datatable javascript code :
var dataTable = $('#table').DataTable({
"processing": true,
"serverSide": true,
"bFilter": false,
"iDisplayLength": configData,
dom: 'Bfrtip',
buttons: ['colvis', 'print', 'csv', 'excel', 'pdf'],
searching: false,
language: {
buttons: {
colvis: 'Show/Hide Columns'
}
},
"ajax": {
url: "getAdvanceCallAnalysisData.json",
data: function(d) {
return $.extend({}, d, {
"offset": 0,
"newRequest": newReq,
"totalRecords": total,
"lookInCol": "aNumber",
"lookInVal": "43543543",
"fromDate": from_date,
"toDate": to_date,
"callingCellId": "",
"CalledCellId": "",
"cdrType": "",
"smsType": "",
"durationFilter": "",
"selectColumns": "",
"sortCol": "",
"sortType": "",
});
},
type: "POST",
error: function() {
alert("error");
},
complete: function(data) {
total = data.responseJSON.recordsTotal;
newReq = 0;
test(total, newReq);
$("#loading_image").hide();
$(".show_datatable").show();
},
"aoColumns": [{
"mData": "aNumber"
}, {
"mData": "bNumber"
}, {
"mData": "cellID"
}, {
"mData": "dateTime"
}, {
"mData": "duration"
}, {
"mData": "imei"
}, {
"mData": "imsi"
}, {
"mData": "operatorId"
}, {
"mData": "mscId"
}, {
"mData": "fileId"
}]
}
});
you can see that my columns name and numbers match with the columns define in ajax response.
I have done same thing for another table and it was working fine but it shows error here. don't know why !!
json response : (It returns 15 records, I posted only two just to make it short)
{"msg":null,"code":null,"status":null,"data":[{"aNumber":"343","bNumber":"3434","cellID":"410-01-831-14770","dateTime":"2017-08-23 17:27:54.0","duration":419,"imei":"22380831696837","imsi":"35340311428389","operatorId":4,"mscId":"5","fileId":"4"},{"aNumber":"3434","bNumber":"5656","cellID":"410-07-1314-28271","dateTime":"2017-08-23 22:02:15.0","duration":785,"imei":"49776303943255","imsi":"35722667519554","operatorId":1,"mscId":"2","fileId":"5"}],"draw":1,"limit":1000,"recordsFiltered":12,"recordsTotal":12}
The most funny part is it shows the correct records and pagination even it display correct rows (with empty data) in datatable. This ajax call returns 15 records. Please see the image below :
Any idea, what is wrong here ?

Unable to display data using jQuery datatables, AJAX and JSON

I'm having a problem displaying my data on my jQuery DataTable using AJAX. I'm using the library from datatables.net. I've tried packaging the JSON in many different formats and nothing is working. I've also messed around with the 'columns' section, interchanging 'title' and 'data.' I only have one event to display for now, but the bottom of the table shows something crazy like 4,000 entries. Here is my code:
<script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/api/EventsApi/GetAll",
"dataSrc": ""
},
columns: [
{ title: "Title" },
{ title: "Template" },
{ title: "Capacity" },
{ title: "Boarding Location" },
{ title: "Status" },
{ title: "Edit / Delete" }
//{ "data": "title" },
//{ "data": "eventTemplateID" },
//{ "data": "locomotive.capacity" },
//{ "data": "boardingLocationStart.city" },
//{ "data": "status" },
//{ "data": "status" }
]
});
});
<div class="title-content">#ViewBag.Title</div>
<div id="dataTable">
<table id="myTable" class="table table-hover" style="text-align: center;">
<tbody id="tBody">
<!-- Table body data goes here -->
</tbody>
</table>
</div>
Here is the JSON that's being returned from the AJAX call:
{"data":[{"tripEventID":1,"extraDetails":"this train has special details","eventName":"ZombieTrainEventName ","departureDate":"\/Date(1443715200000)\/","returnDate":"\/Date(1443718800000)\/","eventCapacityOveride":100,"eventTemplateID":3,"title":"The Zombie Train ","companyID":1,"description":"description of zombie train ride ","boardingClosed":30,"status":1,"boardingLocationStart":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationStartTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnFrom":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"allowFlexableReturnDate":false,"product":[],"productBundle":[{"bundleID":10,"companyID":1,"displayName":" Pumkin Bundle copy Test","price":0.0100,"tax":0.0200,"productList":[]}],"locomotive":{"trainID":1,"companyID":1,"title":"Skunk_Steam ","type":1,"description":"Steam locomotive ","capacity":998,"status":0},"media":{"mediaID":1,"companyID":1,"hero":[],"gallery":[{"mediaDetailID":6,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":null,"url":null},{"mediaDetailID":7,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":"path6","url":"url6"},{"mediaDetailID":8,"formatTypeID":2,"fileName":"testimage7.txt","order":1,"path":"path7","url":"url7"}],"inside":[{"mediaDetailID":1,"formatTypeID":1,"fileName":"testimage.txt","order":1,"path":null,"url":null},{"mediaDetailID":2,"formatTypeID":1,"fileName":"testimage2.txt","order":1,"path":null,"url":null},{"mediaDetailID":3,"formatTypeID":1,"fileName":"testimage3.txt","order":1,"path":null,"url":null}]},"duration":15,"isExclusive":false,"timeAtDestination":45,"isOneWay":false}]}
Like I said, I've tried repackaging the JSON as nested objects and arrays with nothing working. Am I missing something obvious? Any help is appreciated, thank you!
You have to name the columns in your js like the json index keys like this:
$(document).ready(function() {
$('#myTable').DataTable( {
"ajax": "path/to/your/file.json",
"columns": [
{ "data": "title" },
{ "data": "eventTemplateID" },
{ "data": "eventCapacityOveride" },
{ "data": "boardingLocationStart.streetAddress" },
{ "data": "status" },
{ "data": null }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
} );
Note that you can define custom data in tables with the columnDefs option.
And than edit your HTML with something like this:
<table id="myTable" class="table table-hover" style="text-align: center;">
<thead>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</tfoot>
</table>
Here you can find a working fiddle

DataTables Cannot read property 'length' of undefined

Below is the document ready function
Script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#example').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "GetUser.ashx",
"sServerMethod": "POST",
"sAjaxDataProp" : "",
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": "download_link",
"mRender": function ( data, type, full ) {
return 'Detail';
}
} ],
"aoColumns": [
{ "mData": "LoginId" },
{ "mData": "Name" },
{ "mData": "CreatedDate" }
]
});
Below is the respond from server (GetUser.ashx)
[
{
"UserId": "1",
"LoginId": "white.smith",
"Activated": "Y",
"Name": "Test Account",
"LastName": "Liu",
"Email": "white.smith#logical.com",
"CreatedDate": "1/21/2014 12:03:00 PM",
"EntityState": "2",
"EntityKey": "System.Data.EntityKey"
},
More Data...
]
Below is the html table where the data should be put
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th width="15%">User Detail</th>
<th width="15%">LoginID</th>
<th width="15%">Name</th>
<th width="15%">Created Date</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
<tfoot>
<tr>
<th width="15%">User Detail</th>
<th width="15%">LoginID</th>
<th width="15%">Name</th>
<th width="15%">Created Date</th>
</tr>
</tfoot>
</table>
Expected result:
But I came across a problem:
While the page is loading, there was an uncaught exception from the browser:
Cannot read property 'length' of undefined
When I further check, it came from line 2037 of jquery.dataTables.js
var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json );
I checked that the json was valid, but the "aData" was null, why this happen?
Your "sAjaxDataProp" : "" is set to an empty string, which causes this error.
dataTables expects to have a string here to tell under which key your server returned data can be found.
This defaults to aaData, so your json should include this key amongst all others that might be returned or needed by pagination etc.
Normal serversided json:
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],...
Since all values are in aaData you don't need sAjaxDataProp at all.
Modified serverside json:
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"myData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],
Now the values are in myData. so you need to tell dataTables where to find the actual data by setting:
"sAjaxDataProp" : "myData"
Here is a Plunker
As there are 4 columns, add the following in "aoColumns":
"aoColumns": [
{ "mData": null }, // for User Detail
{ "mData": "LoginId" },
{ "mData": "Name" },
{ "mData": "CreatedDate" }
]
For undefined length, I have tried the following code and it's working:
$('#example').dataTable({
"aLengthMenu": [[100, 200, 300], [100, 200, 300]],
"iDisplayLength": 100,
"iDisplayStart" : 0,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "GetUser.ashx",
"sServerMethod": "POST",
"sAjaxDataProp" : "",
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": "download_link",
"mRender": function ( data, type, full ) {
return 'Detail';
}
} ],
"aoColumns": [
{ "mData": null },
{ "mData": "LoginId" },
{ "mData": "Name" },
{ "mData": "CreatedDate" }
]
});
The reference site to know more about aLengthMenu is:
https://legacy.datatables.net/ref#aLengthMenu
If you see this error, look at the json returned from the server, and then make sure that all of your datatable 'mData' values have matching entry. If you are also using a bean, check there as well.
And there is no need specify 'tr', 'td', etc for the table. It is much cleaner if you let jquery do that for you. Here is what my tables look like:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="myTable" style="table-layout:fixed" ></table>
and then my datatable elements specify the width and column title:
{sTitle: "Column A", sWidth: "100px", mData: "idStringFromJson", bSortable: false},
Use $('#example').DataTable({.. (capital D) instead of $('#example').dataTable({..
When I ran into this problem, it was actually the result of an un-applied migration. I had restored a backup of the database, which hadn't yet had one of my recent schema migrations run on it, and once I ran migrations, everything worked fine.

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