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?
Related
I am trying to add a select dropdown to each of my rows in a dataTable from datables version 1.10.23. Both my table data and select data is coming from an API that returns JSON. I have a separate funtion that gets the select data, builds the selected element in JS and returns the whole element. Normally I can append this to a div no problem, but when trying to add to my data tabel I get: [object HTMLSelectElement] in my table instead of the actual select element.
Code:
async function buildRentalReturnTable() {
// table data
let rentalData = await getRentalDetails();
if ($.fn.DataTable.isDataTable('#rentalReturnTable')) {
$('#rentalReturnTable').DataTable().destroy();
}
// returns whole selected element with options populated from API
let selectElement = await buildStatusDDL();
$("#rentalReturnTable").DataTable({
"destroy": true,
"data": rentalData,
"dom": '<"top"i<"clear">><"top d-flex justify-content-between pt-1"lf>rt<"bottom pt-2"p>',
"fixedHeader": true,
"scrollY": "50vh",
"scrollCollapse": true,
"oLanguage": {
"sEmptyTable": "No results found",
"sSearch": "Filter Results:"
},
"columnDefs": [{
"targets": 0,
"orderable": false
}],
"order": [[1, 'asc']],
"columns": [
{
"data": function (data) {
return selectElement
}, "title": "Status"
},
{ "data": "RentalLPID", "title": "RentalLPID" },
{ "data": "SKU", "title": "SKU" },
{ "data": "Description1", "title": "Description1" },
{ "data": "NextRentalDate", "title": "NextRentalDate" },
],
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true
});
}
UI example
Any suggestions?
You need the text (string) of the HTML element - not the element itself (which is an object). Try:
return selectElement.outerHTML
See here for documentation.
I'm using DataTables to fill a table and need some data from a different source. So I started off with render and made a second ajax request by the ID's of what I need the name of.
Here is my code, that will explain it more clearly.
$('#table').DataTable({
"ajax": "/api/url",
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/German.json"
},
"order": [[0, "asc"]],
"pagingType": "simple",
"responsive": {details: false},
"bAutoWidth": true,
"lengthChange": true,
"scrollX": false,
"aoColumnDefs": [{}],
"columns": [
{
"data": "typ_name"
},
{
"data": "mietpreise",
render: function (data, type, row, meta) {
let tmp = [],
currentCell = $("#table").DataTable().cells({
"row": meta.row,
"column": meta.col
}).nodes(0);
data.forEach(function (item) {
$.get("/api/url2/" + item.preis_kundengruppe_id, function (row, status) {
tmp.push(row.data.kundengruppe_name);
});
});
console.log(tmp);
return $(currentCell).text(tmp);
}
},
I'm expecting to have the value of kundengruppe_name in the array like ['case1', 'case2'] but in the console I get this
[]
0: "Endkunden"
1: "Händler"
length: 2
__proto__: Array(0)
So what I want is to find under 0 and 1 and not in the array as expected. What am I doing wrong? What's going on with the array?
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"}],
i created a table with jquery datatables. when I want to filter my table with search bar, the browser gives me an alert DataTables warning: table id=grid - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
this is my code :
$("#grid").dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"searching": true,
"language": {
"url": "/translate/datatables.fa-IR.json"
},
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax": {
"url": serviceBase + "/Auth/Admin/SearchOrders2/",
"type": "GET",
'beforeSend': function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorageService.get("authorizationData").token);
}
},
"columns": [
{ "data": "customerContact", "orderable": true },
{ "data": "isDone", "orderable": true },
{
"mRender":
function (data, type, row) {
var xxx = $scope.name1 = $filter("jalaliDateFromNow")(row["createdDate"]);
return "<span>" + $filter("jalaliDateFromNow")(row["orderCreationTime"]); +'</span>';
}, "orderable": true
},
{ "data": "totalPrice", "orderable": true },
{ "data": "count", "orderable": true },
{ "data": "description", "orderable": true },
{
"mRender": function (data, type, row) {
return '<button class="btn btn-sm btn-circle green tooltips" disabled="disabled"><i class="fa fa-check"></i><span>جزئیات</span></button>'
},
"orderable": false
}
],
"order": [[0, "desc"]]
});
which part of my code is wrong?
I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC