How can I implement stateSaveCallback / "colReorder" / "buttons": ['colvis'] to be enable when the user clicks on a button?
Basically, I need the user to be able to edit the datatable only when he clicks an edit button and the changes to be saved when he press the save button... if the user doesn't press the save button no change will be saved and if he doesn't click on the edit button he won't be able to make any changes... any ideas how to do this?
Currently I have the code below for my dataTable.
$('#resultsTable').DataTable({
"stateSave": true,
// "serverSide": true,
// Rows per page
"lengthMenu": [
[25, 50, 100, 150, 200, 250, -1],
[25, 50, 100, 150, 200, 250, "All"]
],
"dom": '<"top"Bfi>rt<"bottom"lp><"clear">', // Show entries on bottom
// Scrolling table
"scrollY": 600, // Constrain the DataTable to the given height
"deferRender": true, // Elements will be created only when the are required
"scroller": true, // Enable vertical scrolling in DataTables
"scrollX": true, // Scroll horizontal
"colReorder": true, // Column reordering
"buttons": ['colvis'], // Enable column visibility button
// Grouping table
"columnDefs": [{ "visible": false, "targets": 0 }], // Mades target column hidden // if commented ---> Uncaught TypeError: Cannot read property 'style' of undefined
"order": [
[0, 'asc']
], // Sorting based on column
'stateSaveParams.dt': function(e, settings, data) {
data.search.search = "";
// table.columns.visible();
},
// SaveState
'stateSaveCallback': function(settings, data) {
$.ajax({
'url': 'saveDtableState.php',
'data': { name: 'resultsTable', 'state': data },
'dataType': 'json',
'method': 'POST',
"success": function() {},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
},
'stateLoadCallback': function(settings, callback) {
$.ajax({
'url': 'loadDtableState.php',
'data': { name: 'resultsTable' },
'dataType': 'json',
'type': "POST",
success: function(data) {
callback(data);
console.log('test: ' + data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
}
})
will it work if I use this?
$('#saveEdit').on("click", function(){
table.state.save();
});
or will it keep saving the state of the table every time I make a change? (I don't want that). and how to implement the other things? *any tips? *
var run = false;
run = true;
table.state.save(run); // runs the state save function
// SaveState
'stateSaveCallback': function (settings, data) {
if (run == true) {
$.ajax({
'url': 'hfdjs.php',
'data': data,
'dataType': 'json',
'method': 'POST',
"success": function () {},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
}
run = false;
}
Related
function changeStatus() {
$('#dataTable tbody').on('change', '.orderStatus', function () {..code}
}
function showOrdersInModal() {
$('#dataTable tbody').on('click', '.fa-eye-btn', function (e) {...code}
}
function addUrl() {
$('#dataTable tbody').on('click', '.addUrl', function () {..code}
}
function showOrders() {
$.ajax({
type: 'method',
url: 'url',
data: { data },
success: function (response) {
$('#dataTable').DataTable().clear().destroy();
let data = JSON.parse('[' + response.replace(/}{/g, '},{') + ']');
$('#dataTable').DataTable( {
autoWidth: false,
pageLength: 25,
lengthMenu: [[25, 50, 100, 500, -1], [25, 50, 100, 500, 'All']],
data: data,
columns: [
{ data: 'receipt' },
{ data: 'first_last_name' },
{ data: 'contact_no' },
{ data: 'address' },
{ data: 'email' },
{ data: 'url' },
{ data: 'status' },
],
});
showOrdersInModal();
changeStatus();
addUrl();
},
});
}
showOrders();
When I use .off() before .on(), the only last function will execute which is addUrl(); but when I remove the .off() it will trigger the event depending on how many times I click any of each button or element.
Is there a way that I can make the eventHandler trigger once even if I clicked any of the buttons multiple times?
or is there a way to execute all three functions not just the addUrl(); function at the end?
I found the answer and when using the dataTables I cannot access the DOM after the next page so I use drawCallback which like this:
$('#dataTable').dataTable({
drawCallback: function () {
showOrdersInModal();
changeStatus();
addUrl();
},
retrieve: true,
deferRender: true,
data: data,
columns: [
{ data: 'data' },
],
});
then I just use this.
$('.className').off().on('click', function () {..code}
I am using a data table to display data from database and i can perform delete and edit actions.with below code i am able to fetch data from database and perform edit and delete. but the issue is when i delete particular row it is deleted from database but still it is displayed in data table. i made use of "table.destroy();"but it gives the following error.
Uncaught TypeError: $.fn.DataTable.isDataTable is not a function.
code for datatable:
<script>
var table;
if($.fn.DataTable.isDataTable('#sun_project_table') ) {
table=$('#sun_project_table').DataTable();
table.destroy();
//$('#category_table_body').empty();
}
table=$('#sun_project_table').DataTable({
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"iDisplayLength": <?php echo 10; ?>,
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : "<?php echo base_url();?>index.php/Registrationc/displayinfo8",
columns: [
{ "name": "van_village_mapping.van_id", "data": "van_id" },
{ "name": "van_village_mapping.village_id", "data": "village_id" },
{ "name": "Actions", "data": "Actions" }
],
"columnDefs": [
{
}],
"createdRow": function ( row, data, index ) {
},
'fnServerData': function(sSource, aoData, fnCallback)
{
aoData.push();
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
},
"oTableTools": {
"sSwfPath": "assets/media/swf/copy_csv_xls_pdf.swf",
},
"oLanguage": {
"sSearch": "Filter: "
}
});
});
</script>
<script>
function delete_van_village_mapping($1){
$.ajax({
type:"POST",
url: "<?php echo base_url(); ?>index.php/Registrationc/delete_van_village_mapping1",
data:{van_village_mapping_id:$1},
success: function()
{
alert('done!');
}
});
};
</script>
For your question, since you set table = $('#sun_project_table').DataTable({...}); when you initialize the table, thus if you want to check if the table exists before you destroy it, you can just do
if(table) {
table.destroy();
...
}
But I agree with other comment, if you just want to refresh the table, you can just remove the row, or clear the table and fetch it again via ajax.
I finally got my datatable to reload on intervals. But what I'm noticing now is if you scrolled to the right, the table reload will reset the scroll back to the left. The same if you are scrolled down, it will reset back to the top.
I need to stop this from happening.
I've tried all the answers from this post: How to maintain jQuery DataTables scroll position after .draw()
Nothing seems to work. Maybe I'm missing something.
I noticed on this post, the question is using a datatables.scroller.min.js: DataTables save state scroll position
This led me to this: https://cdn.datatables.net/scroller/1.4.2/
But there are so many CSS files there. I'm not sure which one to use, if any should be used at all.
Maybe I do not need any of the above, and I just need to adjust my code below to prevent the scroll reset from happening:
Click event:
$('.searchSubmit').on('click', function() {
updateDataTable();
var idle = 0;
var idleInterval = setInterval(timer, 5000);
$(this).mousemove(function(e){idle = 0;});
$(this).keypress(function(e){idle = 0;});
function timer()
{
idle = idle + 1;
if(idle > 2)
{
updateDataTable();
console.log('table reloaded');
}
}
});
Datatable:
function updateDataTable() {
$.ajax({
url: 'api/railmbs.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR)
{
var jsonObject = $.parseJSON(data);
var table = $('#example1').DataTable({
"data": jsonObject,
"columns": [
{ "data": "BILL" },
{ "data": "CONTAINER" },
// few more columns
],
"iDisplayLength": 25,
"paging": true,
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true,
"autoWidth": true
});
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
}
DOM elements have their current scroll state in elem.scrollLeft/scrollTop,further reading
try this code it rescued me.
var startPos = document.body.scrollLeft
$(selector).DataTable().clear();
$(selector).DataTable().ajax.reload(() => {
document.body.scrollLeft = startPos;
},false);
and for keeping maintaining vertical scroll state try this
var startPos = document.body.scrollTop
$(selector).DataTable().clear();
$(selector).DataTable().ajax.reload(() => {
document.body.scrollTop = startPos;
},false);
Using the DataTable().ajax.reload() will just init the datatable and then make it to reload on a interval (as you're doing currently)
setInterval(function() {
$('#example1').DataTable().ajax.reload(null, false);
}, 5000);
$('#example1').DataTable({
ajax: {
url: "api/railmbs.php",
type: 'POST',
data: data,
dataSrc: function(data) {
return $.parseJSON(data);
}
},
"columns": [{
"data": "BILL"
}, {
"data": "CONTAINER"
},
// few more columns
],
"iDisplayLength": 25,
"paging": true,
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true,
"autoWidth": true
});
As per DataTables Documents resetPaging (the second parameter on false)
Reset (default action or true) or hold the current paging position
(false). A full re-sort and re-filter is performed when this method is
called, which is why the pagination reset is the default action.
This means that neither the pagination(None than it matters if you have scrollY) nor the position of the scroll (X or Y) should reset.
I have a MVC application and I am fetching 5000 records from the database and returns in the JSOn format format in the action and rendering a Jquery.DataTable.js version 1.9.0 grid. The application is returning the data with no delay but it is taking time to render in the grid. Below is the code
$.ajax({
url: "http://locationhost/Mycontroller/myacton", type: "Get", contentType: "application/json; charset=utf-8",
data: { 'param': param1, 'param2': param2, },
dataType: "json",
success: function (data) {
$('#DisableDiv').html("");
var items = '';
var rows = '';
$('#divGrid').DataTable().fnClearTable();
$('#divGrid').DataTable().fnDestroy();
if (data.length > 0) {
$.each(data, function (i, item) {
rows = "<tr>........records......</tr>"
$('#divGrid tbody').append(rows);
});
table = $('#divGrid').DataTable({
"aoColumnDefs": [
{
'bSortable': false,
'aTargets': [0, 8],
}],
"aoColumns": [{ "bSortable": false }, null, null, null, null, null, { "sType": "currency" }, null, { "bSortable": false }],
"bPaginate": true,
"bInfo": true,
"bFilter": false,
"bLengthChange": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 10
});
table.fnSort([[7, 'desc']]);
}
else {
$('#DisableDiv').html("No data available.");
$("#btnDownload").attr("href", "#");
}
}
},
error: function (data) {
$('#DisableDiv').html("");
}
});
Server-side processing is best because when you render a large no of data set records client side
it makes it slow if you want to see please follow below links in that case
http://datatables.net/usage/server-side
example (http://datatables.net/release-datatables/examples/data_sources/server_side.html).
Using the code below, I can get the TableTools buttons to show up on the page, style correctly, and even change the mouse icon on the mouseover event, however the export function is not working. When I click on the button, nothing happens. Don't even get an error message.
The DataTable the TableTools plugin is working on does not exist on the page prior to the user hitting a "Search" button. Once this is done an Ajax call will pull the relevant data and create the DataTable. Again, this part of the program works fine, however when I click on the "Export" buttons (CSV, Excel, PDF)... nothing happens.
jQuery
$.ajax({
type: 'GET',
url: '#Url.Action("PensgcReport", "Home")',
data: { inputArray: inputArray },
traditional: true,
success: function (data) {
//Unpack return object into 2D array
var array = [];
$.each(data, function (key, value) {
var tempArray = [];
$.each(value, function(key, value) {
tempArray.push(value);
});
array.push(tempArray);
});
console.log(array);
$('#ReportTable').dataTable({
"bDestroy" : true,
"aaData": array,
"aoColumns": headers,
"bFilter": false,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bInfo": false,
"aaSorting": [],
"oLanguage": {
"sSearch": "Filter results:"
},
"sDom": 'T<"clear">lfrtip',
"tableTools": {
"sSwfPath": "Content/media/copy_csv_xls_pdf.swf",
"aButtons":
[
{
'sExtends': 'csv',
"sFileName": "PENSGC_Report_" + new Date() + ".csv",
'mColumns': [0, 1]
},
{
'sExtends': 'xls',
"sFileName": "PENSGC_Report_" + new Date() + ".xls",
'mColumns': [0, 1]
},
{
'sExtends': 'pdf',
"sFileName": "PENSGC_Report_" + new Date() + ".pdf",
'mColumns': [0, 1]
},
]
}
});
}
})
HTML
This is the rendered HTML when the page loads (nothing special)
<table id="ReportTable" class="pretty">
</table>
Folder Structure
Change the swf path to:
"sSwfPath": "//cdn.datatables.net/tabletools/2.2.2/swf/copy_csv_xls_pdf.swf"
var table = $('#mytable').dataTable({ YOUR OPTIONS});
var tableTools = new $.fn.dataTable.TableTools(table, {
"buttons": ["copy",
"csv",
"xls",
"pdf",{ "type": "print", "buttonText": "Print me!" } ],
"sSwfPath": "//cdn.datatables.net/tabletools/2.2.2/swf/copy_csv_xls_pdf.swf" });
$(tableTools.fnContainer()).prependTo('#mytable_wrapper');