I have the following problem: I am following these tutorials to be able to save the data in array through each row selected by a checkbox.
https://www.gyrocode.com/articles/jquery-datatables-checkboxes/
https://jsfiddle.net/gyrocode/abhbs4x8/
As in the provided link, I receive data in JSON to load my dataTable, now I am seen in need of, by a button to bring new data to my dataTable for it and added some more functions to the code that is in the link that Provide, and are as follows:
To delete the datatable:
function destroy_data_table(){
var table = $('#example').DataTable({
if (table != undefined){
table .fnDestroy();
}
}
In the click of the button I destroy my datatable and call the function that loads a new one:
$("#btnNewDatatable").click(function (){
destroy_data_table();
new_data();
});
And this is the function that reloads the datatable:
function new_data(){
var table = $('#example').DataTable({
"sAjaxSource": //Here I return in json what my server sends,
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ){
oSettings.jqXHR = $.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": function(result){
fnCallback(result);
}
});
},
responsive: true,
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'width':'1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}]
});
}
My problem is that when loading the new databale, and when selecting a row, this continues to show me the data from the previous datatable, I made a console.log a var rows_selected = []; Which is in charge of storing the data of each selected row, I am badly destroying the table or what could be my mistake?
have you tried
keep this table variable as global for ease.
//Initialize First time
var table = $('#example').DataTable({
......
}
function destroy_data_table(){
table.clear().draw();
}
instead of destroy.
Related
TLDR;
How to stay on the page in datatable using ajax my way?
My problems
User click a button in the table. That particular row will be updated and I will call the fn_GetData() function.
I will fetch the updated data from database into the table again, thus updating the row (actually entire table was updated).
If the row is few page later, when the table reload, it will back to the first page again. How to remain on that particular page?
Btw I tried .ajax.reload( null, false ) is not working
Ajax wrapped in javascript function
function fn_GetData(){
$.ajax({
url: "action/myfile.php",
type: "POST",
data: {'GetData':''},
dataType: "json",
success: function(data) {
if(data.status=='success'){
if ($.fn.DataTable.isDataTable("#myTable")) {
$('#myTable').DataTable().clear().destroy();
}
var myTable = $('#myTable').html(data.table).DataTable({
responsive: {
details: {
type: 'column'
}
},
"dom": 'Bplirtip',
}).columns.adjust().responsive.recalc();
//myTable.ajax.reload( null, false );
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
}
Enable state saving:
$('#example').dataTable( {
stateSave: true
} );
I'm trying to add <tr/> tags dynamically to a DataTable, but I didn't find actual good documentation on how the "adding TR process" is supposed to work. I have this as my DataTables setup:
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
.on("row-reordered", function (e, diff, edit) {
for (var i = 0; i < diff.length; i++)
{
..
}
});
I'm getting the definition of the item in the grid from an MVC action method as an HTML string, via a jQuery AJAX statement:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
var $body = $("#Grid tbody");
$body.append(d);
}
});
The "d" parameter is the HTML for a row; I'm appending it to the body. That adds correctly and but doesn't have the row reorder functionality enabled then. What is the proper way to append to a DataTable, then re-enable whatever functionality?
Use row.add() API method to add a new row instead of appending to the table body.
If d contains string in the following format <tr>...</tr>, you could just use $("#Grid").DataTable().row.add($(d).get(0)) to add a new row.
For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().row.add($(d).get(0)).draw();
}
});
See this example for code and demonstration.
The best option is to use Datatables API's to add rows to the table. As indicated in the previous response you can use either row.add() or rows.add(). The data needs to be in a data structure that matches your Datatables data structure config, ie, arrays or objects.
However it looks like you are receiving HTML structured data and appending directly to the table. In this case Datatables is not aware of the added data. You will need destroy (destroy()) the Datatables table, append your data then re-init Datatables. For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().destroy();
var $body = $("#Grid tbody");
$body.append(d);
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
}
});
I am working with jQuery datatable with state save: true having pagination with 10 records per page. I have 31 records, so on 4th page there is only 1 record.
If I am deleting this record it shows no record found on page, ideally it should move to previous page or first page.
Please help me fixing this.
below is the code
dataTable = $('.tab-pane.active').find('#' + table).DataTable({
"lengthMenu": [[10, 25, 50, 100, 250, 500, '-1'], [10, 25, 50, 100, 250, 500, 'All']],
"processing": true,
"serverSide": true,
"responsive": true,
"scrollX": true,
"autoWidth": false,
"stateSave": true,
"stateSaveParams": function (settings, data) {
data.search.search = "";
},
"aoColumnDefs": [
{'bSortable': false, 'aTargets': [-2, -1]}
],
"initComplete": function ( ) {
$('.overlay').fadeOut();
},
"ajax": {
url: MY_URL,
type: "POST", // method , by default get
data: postObj
}
}).on('preXhr.dt', function (e, settings, data) {
if (settings.jqXHR)
settings.jqXHR.abort();
});
And action to delete is
academic_master.deleteMaster = function (currentClick)
{
var id = currentClick.attr('data-id');
var delete_id = currentClick.attr('delete-id');
var action = currentClick.attr('action');
var data = 'id=' + id + '&delete_id=' + delete_id + '&action=' + action;
$.ajax({
type: 'POST',
url: DELETE_URL,
data: data,
datatype: 'json',
async: false,
success: function (response) {
if (response != '-1' && response != '-20')
{
dataTable.ajax.reload(null, false);
}
});
}
I used to call this above function to delete record, and on success it reloads the table but on same page either if there is no record on that page.
As per the documentation, pagination doesn't reset in your approach.
// user paging is not reset on reload
dataTable.ajax.reload( null, false );
if you use below the line, your pagination would reset. But it would not move to the previous page.
dataTable.ajax.reload();
Suggestion: You would be able to improve the functionality/usability if you follow this approach
https://datatables.net/examples/api/select_single_row.html
//create data table object
var dataTable = $('#tableView').DataTable();
//add class "selected" to the row selected
dataTable.$('tr.selected').addClass('selected');
//I have a button in one of the td of the row. onclicking the button, I assign the class "selected" to the row
$(ths).parents('tr').addClass('selected');
//to delete or remove the row, call the below code
dataTable.row('.selected').remove().draw( false );
I want to refresh table after every 3 seconds. I will appreciate your help. am using the same page to add new records to the database . it does not make any logic for the to refresh the page to view the records they have just saved.
var table = $(".customer-table").dataTable({
"sort": false,
"ajax": {
"url": "{{url('/brah/brah')}}",
"contentType": "application/json",
"type": "GET",
},
"columns": [
{"data": "created_at"},
{
"data": null,
render: function (data, type, row) {
var details = row.first_name + " " + row.last_name;
return details;
}
}
]
});
You need to replace dataTable with DataTable.
And then this should be your solution:
var table = $(".customer-table").DataTable({}); /* fill in your attributes */
setInterval( function () {
table.ajax.reload();
}, 3000 );
https://datatables.net/reference/api/ajax.reload()
I'm using datatable to show list from database mysql
I need to update some input on end of table loading, then I'm using success function but this seems to prevent data rendering
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
},
// EDIT this "my" success function
success: function( data ) {
$('#my_input').val(data.return);
}
}
Json returned is:
{
"data":[[ (datatable value) ]],
"returned":"myvalue"
}
here the jsfiddle
EDIT
http://jsfiddle.net/ntcwust8/95/
Datatable has its own complete event thats called initComplete.
If you redefine success you are overriding Datatable's own function.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
....
....
},
'initComplete':function(settings, json){
alert($('#example tbody tr').length+ ' records on screen');
});
Reference: https://datatables.net/reference/option/initComplete
Update fidle: http://jsfiddle.net/ntcwust8/94/
Just remove the success callback.
success - Must not be overridden as it is used internally in
DataTables. To manipulate / transform the data returned by the server
use ajax.dataSrc (above), or use ajax as a function
Datatable by default handles the success callback, Don't override it.
Instead use complete option of AJAX to do something after data loading.
Updated fiddle
You just need to remove success callback.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
}
}
Edit
you need to use ajax.dataSrc property it will call after ajax finish.
It will work on refresh as well
https://datatables.net/reference/option/ajax.dataSrc
var table = $('#example').DataTable({
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
},
"dataSrc": function (json) {
$("#mydata").val(json.recordsTotal);
return json.data;
}
},
});
here is updated fiddle.
http://jsfiddle.net/2jkg3kqo/2/