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;
}
});
Related
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?!
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',
},
{
]
});
I want add class to td when get list data by ajax
Default my code html
<tr>
<td>#fisrt.System_Code.Code</td>
<td>#fisrt.System_Code.Caption</td>
<td class="text-success">#string.Format("{0:N0}", maden)</td>
<td class="text-danger">#string.Format("{0:N0}", den)</td>
<td class="text-warning nrt-bd" dir="ltr">#string.Format("{0:N0}", maden - den)</td>
</tr>
When i want get list data after filtering , i dont know how to add class
$.ajax({
type: 'GET',
url: '/Record_Professor/Search_Budget/',
data: { from: from, to: to },
success: function (results) {
results.forEach(function (item) {
$('#table_id').dataTable().fnAddData([
item.Code,
item.Caption,
item.Maden,
item.Daeen,
item.Balance
]);
});
},
error: function (error) {
alert('error; ' + eval(error));
}
});
"className": "Classname", is used to add class at run time
$('#table_id').DataTable({
data: data2,
"autoWidth": false,
deferRender: true,
pageLength: 10,
responsive: true,
scrollCollapse: true,
select: {
style: 'os',
selector: 'td:first-child'
},
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
"columnDefs": [{
"className": "Classname",
"targets": [5,2,3,4,9,]
}]
});
$('#example').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 3 ] }
]
} );
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
I am using jquery datatables.net and I have a table with information. In the one column I have true or false values for whether the user is active or not. I am trying to get it so when the value is false, highlight the value. Right now my code for my table settings looks like this:
//Settings for datatable
$('#userTable').DataTable({
"jQueryUI": true,
"serverSide": true,
"ajax": {
"type": "POST",
url: "/Management/StaffGet",
"contentType": 'application/json; charset=utf-8',
'data': function (data) { console.log(data); return data = JSON.stringify(data); }
},
"columns": [
{ "data": "employeeNumber" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "role" },
{
"data": "active",
},
{
"data": "employeeNumber",
"render": function (data, type, full, meta)
{
return 'Edit | Delete ';
}
}
],
"order": [[ 0, "asc"]],
"paging": true,
"deferRender": true,
"processing": true,
"stateSave": false,
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"pageLength": 10,
"pagingType": "simple_numbers",
"searching": false,
"createdRow": function ( row, data, index ) {
if (data[4] == "false" ) {
$('td', row).eq(5).addClass('highlight');
}
}
});`
Then my code for css is:
`<style type="text/css">
td.highlight {
font-weight: bold;
color: red;
}
</style>`
I feel like there is a problem with the setting on the column, any help is appreciated.
Try
$('#userTable').DataTable({
...
"createdRow": function( row, data, dataIndex ) {
//console.log(data[4]);
if ( data[4] == "false" ) {
//console.log($(row).find("td").eq(4).html());
$(row).find("td").eq(4).addClass( 'highlight' );
}},
...
The commented log statements are in there to check you are getting and comparing the correct data.
Tested with datatables 1.10.1