Reload dataTables after button click - javascript

I'm sure there are a few (better) ways to do this, but I can't get any way to work. I'm trying to have datatables load new data (from different data source) when a button is clicked.
Here's what I have:
$(document).ready(function() {
$('#datatable2').dataTable( {
"ajax": {
"url":"simple4.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
});
The initial table (from simple4.php) loads fine. I'd like it to change when I click on a button (with id=option2 in this case), but nothing happens when I click the button.
Just in case, here's the button code in case I'm missing something obvious:
<label class="btn btn-default">
<input type="radio" name="options" id="option2" value="1" autocomplete="off"> Compare 1 and 2
</label>
Not sure what the issue is. Any insight would be helpful.
UPDATE: see answers below explanation of the issue. One thing I didn't do, which apparently makes a major difference is using "dataTable" versus "DataTable". You need a capital D and capital T. Here's the fixed code that's working now:
$(document).ready(function() {
var table = $("#datatable2").DataTable({
"ajax": {
"url":"simple3.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
});
One more thing...my function that was supposed to fire when I clicked on my radio button wasn't working. Had to change from this:
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
To this:
$('input[id=option2]').change(function(){
table.ajax.url( "simple4.php" ).load();
});

First, as the others have said the variable 'table' is not set.
Second, when you call
var table = $('#datatable2').dataTable({.....})
You are returning a jQuery object that won't have access to any of the DataTables API
To get a DataTables API instance you need to make a call like this:
var table = $('#datatable2').DataTable({....});
This should work, assuming that your data returned by your url is properly formed.
Source: https://datatables.net/faqs/#api

I can't try this now, but I think it gonna work:
var table = $('#datatable2').dataTable({...});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
you are not setting var table = ... so when you call table.ajax... table var does not exists

Related

jQuery datatable retain row highlight after reload

I am reloading my datatable on 10 second intervals. When a user clicks on a row, that row will highlight. But when the datatable reloads, the highlight is gone.
Here is the shortened code for my datable:
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
});
});
All of the above works exactly how it's supposed to work. I just need to retain the row highlight after the datatable reloads.
Also, I attempted the answer from this post, but I scrapped it as the row no longer highlights.
Kindly update js file with below changes. Below code will save row clicked in global parameter and then focus the clicked row after ajax call.
var gblIndex = 0; //this will save row clicked index
function setFocus(){
$($('#example1 tbody > tr')[gblIndex]).addClass('selected');
}
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
setFocus(); // this will set focus/highlight row
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
gblIndex = $(this).index(); // this will save the index clicked
});
});
You should review their actual selection documentation to manipulate this. This feature is already built in and setup so on ajax.reload() it will keep your selections.
You can apply classes/styling with their methods as well.
https://datatables.net/reference/option/#select

DataTable cannot click the button after pagination

I have done a datatable and custom it's data but when i click the button on the first column, it only works on the first page and cannot click on other forward pages.
$('#tbl').DataTable( {
responsive: true,
data: data1,
autoWidth: false,
"order": [[ 7, "asc" ]],
"iDisplayLength": 5,
"pagingType": "full_numbers",
"dom": '<"top">rt<"bottom"p><"clear">',
"oLanguage": {
"sEmptyTable": "Not Record"
},
"columnDefs": [
{ "visible": false, "targets": [ 6,7,8 ] }
],
"columns": [
{},{"sClass": "dt-body-justify"},{},{},{},{},{},{},{},{}
]
} );
BUT when for the click function in live mode, it still cannot work
$('#tbl tbody tr #edit_current_product').delegate('a', 'click', function () {
.......
} );
id's must be unique. We dont know your markup but
$('#tbl tbody tr #edit_current_product').delegate('a', 'click', function ()
seems utterly wrong. Either you have multiple <a>'s with the same id #edit_current_product or the right thing actually happens, you have paginated away from the page where #edit_current_product is present.
I guess that what you really want is
$('#tbl').on('click', 'tbody tr a', function()
or use a class instead of an id
$('#tbl').on('click', 'tbody tr .edit_current_product', function()
BTW, why
"columnDefs": [
{ "visible": false, "targets": [ 6,7,8 ] }
],
"columns": [
{},{"sClass": "dt-body-justify"},{},{},{},{},{},{},{},{}
]
you just need
"columnDefs": [
{ "visible": false, "targets": [ 6,7,8 ] },
{ "sClass": "dt-body-justify", targets : [1] }
]

DataTables ajax.reload when keeping pagination it jumps to the bottom of the page

I'm using jQuery DataTables with ajax sourced data.
I have to keep the data up to date every 30 seconds without refreshing the page, and ajax.reload() is the function that I need.
I put ajax.reload() inside a setInterval function.
And all works right (if you stay on page 1). But when you surf the table on page 2 or 3, when setInterval is fired, it gets you back to the page 1.
So ...
Looking to docs at this url: http://datatables.net/reference/api/ajax.reload()
if I pass "false" as second parameter it holds the current paging position, and paging is not reset on reload. BINGO!
It works! BUT ... I have a new problem that a tried to solve the all day and now I'm stuck. That's why I post this question.
It keeps paging but if you are not on page 1, every time that ajax.reload() is fired, the page scrolls (jump directly) to the bottom.
It's very unfriendly, unreadable, unusable.
I don't know WHY the page scrolls to the end-bottom.
I post a link to my simple datatable js that I use on my page.
jsfiddle
var url = table.data('url');
var filterType = table.data('filtertype');
var options = {
"ajax": {
"url": url,
"type": "GET",
"data": function (d) {
d.contact_type = filterType
// this variable will set by server when page load. It should be "lead", "prospect", "client". Leave empty to get all.
}
},
"columns": [
{"data": "html_is_company"},
{"data": "name"},
{"data": "html_type_label"},
{"data": "created"},
{"data": "last_update"},
{"data": "html_actions"},
{"data": "tsu"},
{"data": "business_name"}
],
"bLengthChange": false,
"pageLength": 20,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columnDefs": [
{
"targets": [ 7 ],
"visible": false,
"searchable": true,
},
{
"targets": [ 6, 7 ],
"searchable": false,
"visible": false
},
{
"targets": [0, 5],
"searchable": false,
"orderable": false
},
{
"targets": [ 4 ],
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT, 'it').fromNow();//.format(DATE_TIME_FORMAT);////;
}
},
{
// Sort column 4 (formatted date) by column 6 (hidden seconds)
"orderData":[ 6 ],
"targets": [ 4 ]
}],
"order": [[4, "desc"]],
"search": "_INPUT_",
"language": {
"sSearchPlaceholder": "Cerca...",
"paginate": {
"previous": '<i class="icon wb-chevron-left-mini"></i>',
"next": '<i class="icon wb-chevron-right-mini"></i>'
},
//"url": "//cdn.datatables.net/plug-ins/1.10.9/i18n/Italian.json"
}
};
var datatable = table.DataTable(options);
this.setDataTable(datatable);
setInterval(function(){
datatable.ajax.reload(null, false);
}, 5000);
My solution:
"fnDrawCallback": function(data) {
$(".paginate_button > a").on("focus", function() {
$(this).blur();
});
}
jacopo.galli's solution was very clunky when I implemented for my table, but it's probably because my code was a mess. The idea of adding blur() is great thou.
I rewrite his code a bit:
$(window).scroll(function(){
$(".paginate_button > a").blur();
});
The buttons on the pagination bar will be "unfocused" once the page scrolls.
So your final code should look like this:
var url = table.data('url');
var filterType = table.data('filtertype');
var options = {
"ajax": {
"url": url,
"type": "GET",
"data": function (d) {
d.contact_type = filterType
// this variable will set by server when page load. It should be "lead", "prospect", "client". Leave empty to get all.
}
},
"columns": [
{"data": "html_is_company"},
{"data": "name"},
{"data": "html_type_label"},
{"data": "created"},
{"data": "last_update"},
{"data": "html_actions"},
{"data": "tsu"},
{"data": "business_name"}
],
"bLengthChange": false,
"pageLength": 20,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columnDefs": [
{
"targets": [ 7 ],
"visible": false,
"searchable": true,
},
{
"targets": [ 6, 7 ],
"searchable": false,
"visible": false
},
{
"targets": [0, 5],
"searchable": false,
"orderable": false
},
{
"targets": [ 4 ],
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT, 'it').fromNow();//.format(DATE_TIME_FORMAT);////;
}
},
{
// Sort column 4 (formatted date) by column 6 (hidden seconds)
"orderData":[ 6 ],
"targets": [ 4 ]
}],
"order": [[4, "desc"]],
"search": "_INPUT_",
"language": {
"sSearchPlaceholder": "Cerca...",
"paginate": {
"previous": '<i class="icon wb-chevron-left-mini"></i>',
"next": '<i class="icon wb-chevron-right-mini"></i>'
},
//"url": "//cdn.datatables.net/plug-ins/1.10.9/i18n/Italian.json"
}
};
var datatable = table.DataTable(options);
this.setDataTable(datatable);
$(window).scroll(function(){
$(".paginate_button > a").blur();
});
setInterval(function(){
datatable.ajax.reload(null, false);
}, 5000);
I've found a solution that works for me.
The problem was the "focus" on DataTables pagination links.
When user clicks on a link page, it sets a focus on that link and when ajax.reload() is fired the browser gets you where the focused element is. My table is the last element of the page so the page scrolls to the bottom.
I got it when I clicked on another area of the page after clicked on page 2 link. The "jumping" problem was gone.
So, I solved firing a blur() when DataTables has complete its initialization and when ajax.reload() has finished (thanks to the first parameter that allows you to define a function).
In DataTables options I added this:
"initComplete": function(settings, json) {
$(".paginate_button > a").on("focus", function(){
$(this).blur();
});
},
and then, in setInterval:
setInterval(function(){
datatable.ajax.reload(function(){
$(".paginate_button > a").on("focus", function(){
$(this).blur();
});
}, false);
}, 30000);
Don't know if this is the "best solution" ... but it works and could helps someone.

How to remove the next/previous tabs after the jQuery dataTable initialized from jSON?

A jQuery table is initialized from jSON
I know that it will be only one row, so I do not need to show the next/previous tabs after the table. Nevertheless they are displayed.
Is there any way of removing them?
The code for the table:
table = $("#retrievedTable").dataTable({
"bServerSide" : true,
"sAjaxSource" : "/cm/credit/getretrievedTable.json",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "orderNumber", "value": $( "#orderNumberInput" ).val() } );
},
"bProcessing" : true,
"bInfo" : false,
"bRetrieve" : true,
"bDestroy" : true,
"bAutoWidth": false,
"bLengthChange": false,
"iDisplayLength": 20,
"aoColumnDefs": [{
"mRender": function ( data, type, row ) {
return moment(data).format("MM/DD/YYYY");
},
"aTargets": [ 0 ],
"bPaginate": false
}]
});
The only answer I can come up with is to hide it instead of removing it. You can do this by adding this to your css:
.dataTables_paginate {
display: none;
}
I've tried it with the example on the website. The css class was found on this page.

jQuery datatable - fnReloadAjax does not override sAjaxSource

I have the following code which shows all rows by default and when clicking the .view-unread-rows button the datatable should only show unread rows. However, it does not appear to be running the reload query.
$(".view-unread-rows").click( function(e) {
e.preventDefault();
message_table.fnReloadAjax("/letters/ajax/T");
message_table.fnDraw();
});
$(".view-all-rows").click( function(e) {
e.preventDefault();
message_table.fnReloadAjax("/letters/ajax/F");
message_table.fnDraw();
});
message_table = $('.message_table').dataTable({
"sPaginationType": "bootstrap",
"iDisplayLength": 10,
"iDisplayStart": 0,
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "POST",
"sAjaxSource": "/letters/ajax/F",
"sDom": '<"top">rt<"bottom"><"clear">',
"aaSorting": [[3, 'desc']],
"aoColumns": [
{ "bSortable": false },
{ "bSortable": true },
{ "bSortable": false },
{ "bSortable": true }
],
"oLanguage": {
"sEmptyTable": "No results"
}
});
I have had this working but I've changed something at some point and it's now stopped. Any ideas?
EDIT:
OK, oddly enough, this seems to work fine if there are no results for clicking on .view-unread-rows.
Still no clue though.
$(this).on('click', '.view-unread-rows', function(e) { ...

Categories