Best Practice to Lazy Load Huge Data into a Table - javascript

I have a fiddle that make an AJAX to get this Data to render a table. My goal is load only 10 rows during the first initial page load.
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Account ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
</table>
JavaScript
$(document).ready(function() {
$('#example').DataTable( {
"bPaginate": true,
"processing": true,
"bServerSide": true,
ajax: {
url: 'https://api.myjson.com/bins/1egsx',
dataSrc: 'data'
},
columns: [
{ data: 'account_id' },
{ data: 'name' },
{ data: 'email' }
],
"deferRender": true,
"deferLoading": 10,
} );
});
I've been trying to use datatables JavaScript plug-in, but it doesn't seem to work.
Are there any other scripts/plug-ins/frameworks I should look into?

Related

Getting 500 while adding data to datatables in javascript .net mvc

So i'm trying to add data to datatable, i'm relatively new to Web Applications, i'm more of a mobile app developer
I've looked into a few examples and i've come up with a solution to do it, but for some reason i'm getting this error on chrome
DataTables warning: table id=personaliseDatatable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
And if i check the console i'm getting Internal Server Error 500, but in fact the controller is getting triggered and i'm able to get the data from the repository, but its not able to return is what i'm able to understand
This is my method in controller
public JsonResult GetAllCapacityData()
{
try
{
var data = _capacityService.GetAllData(null).ToList();
return Json(new
{
data = data
});
}
catch (Exception ex)
{
_logger.Error("WebApp -> AreaMappingController -> GetAllData -> Catch -> ", ex);
throw;
}
}
and this is my ajax request
$(document).ready(function() {
if ($('#loaderDiv').hasClass("show")) {
$('#loaderDiv').removeClass("show");
}
GetCapacityData();
});
function GetCapacityData() {
$('#personaliseDatatable').DataTable({
responsive: true,
processing: false,
serverSide: false,
searching: true,
scrollX: true,
bDestroy: true,
"scrollX": true,
aaSorting: [0, 'desc'],
ajax: {
url: '#Url.Action("GetAllCapacityData", "Capacity")',
type: 'POST'
},
language: {
search: "",
searchPlaceholder: "Search...",
sInfoFiltered: ""
},
columns: [{
"render": function(data, type, full, meta) {
return meta.row + 1;
}
},
{
data: "data.ZoneMaster.ZoneName"
},
{
data: "CateogoryName"
},
{
data: "SubCateogoryName"
},
{
data: "ServiceType"
},
{
data: "UserType"
},
{
data: "Division"
},
{
data: "SlotName"
},
{
data: "AllowBooking"
},
{
data: "HoursBlockAhead"
},
{
data: "DaysOpenAheadForBooking"
},
{
data: "MaximumOrderCapacity"
},
{
mRender: function(data, type, row) {
return '<a class="actionLinks" data-toggle="tooltip" title="View Details" style="cursor:pointer;" onclick="EditCapacity(' + row.CapacityPlannerId + ')">Edit</a>';
},
sortable: false,
searchable: false
}
]
});
alert(data.ZoneMaster.ZoneId);
}
And this my Datatable
<div class="card-body">
<table style="width:100%" class="table table-striped table-hover table-bordered" id="personaliseDatatable">
<thead>
<tr>
<th>#</th>
<th>Zone</th>
<th>Cateogory</th>
<th>Sub Cateogory</th>
<th>Service Type</th>
<th>User Type</th>
<th>Division</th>
<th>Slot Name</th>
<th>Allow Booking</th>
<th>Hours to Block Ahead</th>
<th>Days Open Ahead</th>
<th>Max. Order Capacity</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Error on console
POST http://localhost:53201/Capacity/GetAllCapacityData 500 (Internal Server Error)
Any Help would be deeply appreciated

Two footers not printed in pdf and excel format when clicked in button in jquery datatable

Actaullay I have buttons to save in pdf and excel format.I have two footers coming from json as Total and Percentage.When i click the Button then only Total footer is coming but the Percentage row is not coming in the pdf and excel files.I need to show both the footer but it is not coming.
<table id="report46Table" class="display responsive nowrap" style="width: 100%">
<thead>
<tr>
<th>Disturbance</th>
<th>Zero</th>
<th>Minor</th>
<th>Medium</th>
<th>Major</th>
<th>Total</th>
<th>Occurance</th>
</tr>
</thead>
<tfoot>
<tr id="fTotal">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr id="fPercentage">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
script to load the datatable is:
<script>
$(document).ready(function() {
var report46Data = [];
var report46Footer = null;
var report46Table = $('#report46Table').DataTable({
data : report46Data,
dom: 'Bfrtip',
buttons: [
'copy',
{
extend: 'excel',
footer: true,
text : 'Export to Excel',
messageTop: 'Records of forest disturbances in the forest',
filename: function(){
return 'report46';
},
},
{
extend: 'pdfHtml5',
footer: true,
//orientation : 'landscape',
pageSize: 'TABLOID',
text : 'Export to Pdf',
messageTop: 'Records of forest disturbances in the forest',
title: '',
filename: function(){
return 'report46';
},
},
],
ordering: false,
"paging" :false,
columns : [ {
"data" : "disturbanceName"
}, {
"data" : "iZero"
}, {
"data" : "iMinor"
}, {
"data" : "iMedium"
} ,{
"data" : "iMajor"
},{
"data" : "total"
},{
"data" : "occurance"
}],
"footerCallback" : function(row, data, start, end, display) {
var api = this.api();
if (report46Footer) {
$($("#fTotal")[0].cells[0]).html(report46Footer[0].disturbance);
$($("#fTotal")[0].cells[1]).html(report46Footer[0].iZero);
$($("#fTotal")[0].cells[2]).html(report46Footer[0].iMinor);
$($("#fTotal")[0].cells[3]).html(report46Footer[0].iMedium);
$($("#fTotal")[0].cells[4]).html(report46Footer[0].iMajor);
$($("#fTotal")[0].cells[5]).html(report46Footer[0].total);
$($("#fTotal")[0].cells[6]).html("");
$($("#fPercentage")[0].cells[0]).html(report46Footer[1].disturbance);
$($("#fPercentage")[0].cells[1]).html(report46Footer[1].iZero);
$($("#fPercentage")[0].cells[2]).html(report46Footer[1].iMinor);
$($("#fPercentage")[0].cells[3]).html(report46Footer[1].iMedium);
$($("#fPercentage")[0].cells[4]).html(report46Footer[1].iMajor);
$($("#fPercentage")[0].cells[5]).html(report46Footer[1].total);
$($("#fPercentage")[0].cells[6]).html("");
}
}
});
$.ajax({
url : A_PAGE_CONTEXT_PATH + "/api/report46/all",
method : "GET",
dataType : "json",
success : function(response) {
report46Data = response.dataList;
report46Footer = response.footer;
report46Table.rows.add(report46Data).draw();
}
});
});
</script>

How to reload table data using DataTables, Ajax call & Json response?

I have a table that is generated through Thymeleaf. I would like to refresh the contents of the table using jQuery.
<table class="table table-hover" id="main-table">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep date</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" id="repDate" th:text="${#findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
<td class="text-center" id="hashrate" th:text="${#findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
</tr>
</tbody>
</table>
I have come up with such function to update table contents every 8s:
$(document).ready(function() {
var table = $('#main-table').DataTable({
ajax: {
url: '/refresh',
dataSrc:''
},
paging: true,
lengthChange: false,
pageLength: 20,
stateSave: true,
info: true,
searching: false,
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] }
],
"order": [[ 0, "asc" ]]
});
setInterval(function(){
table.ajax.reload();
}, 8000);
});
Here's the JSON response:
[{
"id":1,
"repDate":{
"offset":{ },
"nano":880042000,
"year":2018,
"monthValue":4,
"dayOfMonth":25,
"hour":12,
"minute":58,
"second":53,
"month":"APRIL",
"dayOfWeek":"WEDNESDAY",
"dayOfYear":115
},
"hashrate":5114926.0
},...more entries
]
An empty table prints and I keep getting an error:
Uncaught TypeError: Cannot read property 'reload' of undefined
There's also an alert pop-up saying:
Data Tables warning: table id=main-table - Requestem unknown parameter '0' for row 0 column 0. For more information about this error, please see: http://datatables.net/tn/4
EDIT
I moved table declaration outside the function. Now I just keep getting the warning.
EDIT 2
I did as you stated, the data keeps refreshing, but there are still few issues.
First of all, my stateSave: true property stopped working, so when the table is reloaded it always gets back to the first page.
Secondly, I lost all my styling (class="text:center" for example) and on:click property that were originally in my html file.
Try to declare the table before the $(document).ready :
var table;
$(document).ready(function() {
table = $('#main-table').DataTable({"serverSide": true, ...})
setInterval(function(){
table.ajax.reload();
}, 8000);
})
The error is related to your column definition, try this way to define columns :
"columnDefs": [
{
"targets": 0,
"data": "id",
},
{
"targets": 1,
"data": "repDate",
},
{
"targets": 2,
"data": "repDate",
}
]

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

jQuery datatables TypeError: b is null

I am facing with a error fired by Firebug when using a jquery datatables plugin
The table is like this:
<table id="dt_cursuri" class="table table-striped table-bordered dTableR">
<thead>
<tr>
<th data-class="expand">Curs</th>
<th data-hide="phone,tablet" data-name="Assign">Domeniu</th>
<th>Tip</th>
<th>Data modif</th>
<th class="centered-cell">Actiuni</th>
</tr>
</thead>
<tbody>
<tr>
<td class="dataTables_empty" colspan="6">Fetching data from server</td>
</tr>
</tbody>
</table>
The datatables initialization:
var oTable;
var responsiveHelper = undefined;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
var oTable = $('#dt_cursuri');
oTable = $('#dt_cursuri').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "bootstrap",
"sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"sAjaxSource": "view/cursuri/server_side.php",
autoWidth : false,
"fnPreDrawCallback": function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper(oTable, breakpointDefinition);
}
},
"fnDrawCallback" : function (oSettings) {
responsiveHelper.respond();
},
"fnRowCallback": function( nRow, aData ) {
responsiveHelper.createExpandIcon(nRow);
},
"aoColumns": [
//{ "sClass": "center", "bSortable": false, sWidth: '2%', "bVisible": false },
{ sWidth: '35%' },
{ sWidth: '25%' },
{ sWidth: '20%' },
{ sWidth: '10%' },
{ "sClass": "center", sWidth: '10%', "bSortable": false }
],
"aaSorting": [[2, 'asc']]
} );
The server side json file is working corectly. The same code is used in other tables that work perfect, but this one is not
Could someone help me?
The error is fired for this line from jquery.datatables.js:
!a.sLoadingRecords && (c && 'Loading...' === b.sLoadingRecords) && D(a, a, 'sZeroRecords', 'sLoadingRecords');
I will answer this question on my own thanks to developers of jQuery Datatables.
The problem was in the server side processing. When using diacritics the datatable is messing with the data so you have to actually control the diacritics with utf8_encode() php function

Categories

Resources