jQuery Datatable preInit event not firing - javascript

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',
},
{
]
});

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?!

Show "All" pages in DataTables along with responsive tables and other attributes

I dont know how to to merge the function of my current attibutes of responsive and fixed header etc with Show "All" list function like it has in this one https://datatables.net/examples/advanced_init/length_menu.html
I dont know how to do it pls help here is my current function
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
var table = $('#example').DataTable({
responsive: true,
paging: false,
columnDefs: [{
searchable: false,
orderable: false,
targets: 0,
}],
order: [
[1, 'asc']
],
});
new $.fn.dataTable.FixedHeader(table);
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});
</script>
i am unable to merge the function with show "All" page length menu in javascript please help.
also please allow me run snippet im very new to js
thank you
var table = $('#example').DataTable({
responsive: true,
paging: false,
// Add this line
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
columnDefs: [{
searchable: false,
orderable: false,
targets: 0,
}],
order: [
[1, 'asc']
],
});
new $.fn.dataTable.FixedHeader(table);

Jquery datatables amount of pages

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

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

how to add data in datatable?

I am trying to add data dynamically in datatable.I have initialized table on document.ready and created an instance of it.After that, I am trying to add data in the table using instance.
$(document).ready(function() {
//Initialize tooltips
table_sgdFile_list_linked = $('#sgdFile_list_linked').DataTable({
bSort: false,
destroy:true,
bLengthChange: false,
pageLength: 4,
columns: [{
title: "Name"
},
{
title: "Action"
}
]
});
});
I am trying to bind the data
table_sgdFile_list_linked.data(dataSet)
but it is not working.
my_list = $('#my-table-html-id').DataTable( {
"processing": true,
"serverSide": false,
"paging": true,
"bLengthChange" : true,
"bFilter": false,
"pageLength": 10,
"info": false,
"ordering": true,
"ajax": "PATH-OF-MY-API",
"columnDefs": [
{
"render": function ( data, type, row ) {
var html = data + " Modified!";
return html;
},
"orderable": false,
"targets": 1 //Last column
},
],
})
you can try this:
to add 1 row: table_sgdFile_list_linked.row.add(rowJson).draw();
to add multiple rows: table_sgdFile_list_linked.rows.add(rowsJson).draw();
following worked for me :
table_sgdFile_list_linked.clear().draw();
$('#sgdFile_list_linked').dataTable().fnAddData(trHTML);

Categories

Resources