Jquery datatables amount of pages - javascript

I'm trying to use jquery datatables with backend on Spring HATEOAS which returns HAL document with structure:
{
"_embedded": {...},
"_links": {...},
"page": {
"size": 10,
"totalElements": 15,
"totalPages": 2,
"number": 0
}
}
Currently my datatable settings looks like:
const table = TABLE_ELEMENT.DataTable({
processing: true,
ordering: false,
serverSide: true,
paging: true,
pagingType: 'numbers',
pageLength: 10,
lengthChange: false,
recordsTotal: 15,
searching: false,
ajax: {
type: 'GET',
url: '/api/employees',
dataSrc: data => data._embedded.employees,
},
columns: [
{data: 'name'},
{data: 'email'},
{data: 'phone'},
{data: 'birthDay'}
]
});
But the problem is that I can't properly setup number of pages I have. If I use serverSide: true my table has infinite amount of pages, if i use serverSide: false instead my table has only 1 page. How to solve this?
To switch between pages I use code:
TABLE_ELEMENT.on('page.dt', () => {
table.ajax.url('/api/employees?page=' + table.page.info().page);
});

to solve this I replaced property dataSrc, with:
dataFilter: (data) => {
let json = JSON.parse(data);
json.recordsTotal = json.page.totalElements;
json.recordsFiltered = json.page.totalElements;
json.pageLength = json.page.size;
json.data = json._embedded.employees;
return JSON.stringify(json);
}
also properties
pageLength: 10,
recordsTotal: 15
can be removed

Related

Show json value in jquery ajax datatables result

I add json data in database like this (in database column social):
{"twitter":"test","instagram":"test1","linkedin":"test2"}
for show result in datatables:
var tableUser = $('#table-user').DataTable({
dom: 'rt<"card-footer"<"row" <"col-md-6"i> <"col-md-6"p>>>',
processing: true,
serverSide: true,
autoWidth: false,
order: [
[1, 'asc']
],
ajax: {
url: '<?= route_to('admin/user/manage') ?>',
method: 'GET'
},
columnDefs: [{
orderable: false,
targets: [0, 4, 5]
}],
columns: [
{
'data': function(data) {
return data.social
},
}
]
});
Result is(return data.social):
{"twitter":"test","instagram":"test1","linkedin":"test2"}
In action I need to specific value like: twitter or instagram. How to show this result?!

jQuery Datatable preInit event not firing

I would like to access the dropdown list for length display of the jQuery Datatable before the data is loaded in the table, i have a problem that whenever the user select the lenght of records to display in the table , the table resize and trigger window.resize() and i want to access the dropdown list after the table initialization but before the data is loaded, here is what i trying to do but it doesn't work.
let table = $('#data-table').DataTable();
$(document).on('preInit.dt', function (e, settings)
{
$('select[name=data-table_length]').click(function ()
{
console.log('dropdown selected');
window_resize = false;
});
});
table = $('#data-table').DataTable({
destroy: true,
serverSide: false,
autoWidth: false,
paging: true,
order: [[1, 'asc']],
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
ajax: {
url: '/Observer/GetActiveClientsByProfileId',
type: 'POST',
data: {
ProfileId: profileId
},
dataSrc: ''
},
columns: [
{
title: 'Zone',
data: 'LastKnownZone',
},
{
]
});

Server-sided DataTable rows count function returns only the total number of the current page

I have the following datatable that is set to server side mode:
As you can see on footer, the total of rows is 21.
But, when I call the function that should return the total of rows, it only returns 10, that is the total of the current page:
How to make it returns 21 instead of 10?
Here's the client-side code of the datatable:
tableOcorrenciaAgendadosHoje = $('#tableOcorrenciaAgendadosHoje').DataTable({
ajax: {
url: "/Ocorrencia/GetOcorrencias",
type: "POST",
datatype: "json",
data: function (d) {
d.aba = "agendadosHoje";
}
},
aoColumnDefs: [{
orderable: false, aTargets: [0]
}],
order: [],
columns: colunas,
scrollX: true,
scrollCollapse: true,
fixedColumns: {
leftColumns: 2,
},
language: {
url: "/Content/js/Portuguese-Brasil.json"
},
serverSide: "true",
processing: "true",
});
According to the documentation:
https://datatables.net/reference/api/page.info()
The following should work in your case:
$(table_id).DataTable().page.info().recordsTotal
I found the solution. I simply added the following function to the datatable:
fnDrawCallback: function () {
self.QtdOcorrenciasAgendadosHoje = this.api().page.info().recordsTotal;
}
It always returns the total of records, even when the table is updated.

passing dynamic value from AJAX to custom parameter in jQuery dataTable

I'm using dataTable with server side processing. I want to send token as custom parameter to the server. Token is set by AJAX. When AJAX request on dataTable fired, token parameter that send always null. I think it is because AJAX request on dataTable fired before get token process finished. Here are ways that I already tried.
1. Using ajax.data
function GetToken() {
var token;
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
token= token;
});
return token;
}
var dataTable = $('#dataTable').DataTable({
serverSide: true,
pagingType: 'full_numbers',
scrollY: false,
scrollX: true,
sort: false,
fixedColumns: true,
autoWidth: true,
language: {
paginate: {
first: "<<",
previous: "<",
next: ">",
last: ">>",
}
},
pageLength: 10,
lengthMenu: [[2, 5, 10, 25, 50], [2, 5, 10, 25, 50]],
columns: [
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true },
{ "data": "Gender", "autoWidth": true },
],
ajax: {
url: '#Url.Action("LoadData", "Student")',
type: 'POST',
data: { token: GetToken() }
dataSrc: "Data"
}
});
2. Using preXhr.dt
var dataTable = $('#dataTable')
.on('preXhr.dt', function (e, settings, data) {
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
data.token = token;
});
})
.DataTable({
serverSide: true,
pagingType: 'full_numbers',
scrollY: false,
scrollX: true,
sort: false,
fixedColumns: true,
autoWidth: true,
language: {
paginate: {
first: "<<",
previous: "<",
next: ">",
last: ">>",
}
},
pageLength: 10,
lengthMenu: [[2, 5, 10, 25, 50], [2, 5, 10, 25, 50]],
columns: [
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true },
{ "data": "Gender", "autoWidth": true },
],
ajax: {
url: '#Url.Action("LoadData", "Student")',
type: 'POST',
dataSrc: "Data"
}
});
3. Add looping for delay on preXhr.dt
var isTokenChange = false;
var dataTable = $('#dataTable')
.on('preXhr.dt', function (e, settings, data) {
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
data.token= token;
isTokenChange = true;
});
while(!isTokenChange) {
}
isTokenChange = false;
})
.DataTable({
serverSide: true,
pagingType: 'full_numbers',
scrollY: false,
scrollX: true,
sort: false,
fixedColumns: true,
autoWidth: true,
language: {
paginate: {
first: "<<",
previous: "<",
next: ">",
last: ">>",
}
},
pageLength: 10,
lengthMenu: [[2, 5, 10, 25, 50], [2, 5, 10, 25, 50]],
columns: [
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true },
{ "data": "Gender", "autoWidth": true },
],
ajax: {
url: '#Url.Action("LoadData", "Student")',
type: 'POST',
dataSrc: "Data"
}
});
For third way, it's works but I think it's not a good solution. My question is what is a good solution to hold or delay ajax request on datatable until token has received?
You can chain your calls, Only when you receive a token fire the datatable initialization.
function GetToken() {
var token;
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
initializeTable(token);
});
}
initializeTable(token){
// Here initialize ur data table with the passed token.
}
This works for me:
dataTable.context[0].ajax.data.yourCustomValue = value;
Since my variable name is bwsValue:
var dataTable = $('#users-grid').DataTable( {
"dom": 'lrtip',
"order": [[ 0, "asc" ]],
"processing": true,
"serverSide": true,
"ajax":{
url :"users_list.php?active="+active,
"data": {
"bwsValue": 1
},
type: "post",
}
});
I can now set the data to:
dataTable.context[0].ajax.data.bwsValue = 2;
You do not want to do a async request in this case, so instead of using $.get try something like this (async:false):
$.ajax({
type: "GET",
async:false,
url: "/User/GetToken?_=" + new Date().getTime(),
success: function(token, textStatus, xhr) {
data.token = token;
}
});

Update ajax data programatically for jQuery datatables

I have a jQuery datatable with an ajax datasource defined like so:
var selected_ids = [];
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': {
'member_ids' : JSON.stringify(selected_ids)
},
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});
$('#available_members').on('click', '.select', function(e) {
e.preventDefault();
member_id = $(this).data('member-id');
selected_ids.push(member_id);
selected.api().ajax.reload();
});
As you can see I am updating the contents of selected_ids manually and I want to then refresh the datatable. This is working except that when the datatable reloads and does the ajax call the member_ids parameter that it passes to the server is still empty. Do I have to update the data property of the ajax call manually before reloading the table and if so how do I do that?
I fixed it I used a closure for the data attribute instead like so:
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': function ( d ) {
d.member_ids = selected_ids;
return d;
}
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});

Categories

Resources