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" }
]
})
}
});
Related
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 have a table at which I am using jQuery Datatable. The table is being updated every 15 seconds with new data. I am using the latest version of Datatable.
How can I re-initialise the Datatable with new data without using clear method, which impacts the UI?
My Code:
jQuery.ajax({
type: 'POST',
url: /list_tasks',
data: ajaxData,
spinner: true,
success: function (response) {
$('#task_table').html(response.html)
if ( $.fn.DataTable.isDataTable('#task_table')) {
$('#task_table').DataTable().destroy();
}
var dataTable=$('#task_table').DataTable({
deferRender:true,
destroy: true,
scrollCollapse: true,
scroller: true,
scrollY: "200px",
bFilter:false,
bInfo: false,
bLengthChange:false,
initComplete: function(settings, json) {
},
fnDrawCallback:function(){
}
});
}
});
Instead of reinventing the wheel you should rely on dataTables built in ajax feature. If you do that, you can update the table very easy by using ajax.reload() :
var dataTable =$('#task_table').DataTable( {
ajax: {
url: '/list_tasks',
data: ajaxData
},
deferRender:true,
scrollCollapse: true,
scroller: true,
scrollY: "200px",
bFilter:false,
bInfo: false,
bLengthChange:false,
initComplete: function(settings, json) {
},
fnDrawCallback:function(){
}
});
setInterval(function() {
dataTable.ajax.reload()
}, 15000);
Update. You will never be able to prevent flickering or impact on the UI if you repeately inject and remove a table to the DOM, and instantiate it as a dataTable afterwards. Another approach could be to separate your table code in a different PHP script and place it inside an iframe :
<iframe src="table.php" id="table"></iframe>
Then update the iframe itself each 15 secs :
setInterval(function() {
$('#table')[0].contentWindow.location.reload(true);
}, 15000);
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.
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/
How to use dataTables to instantiate the table does not load data (server mode),then loading data when i click on a button.If serverSide is set to true at initialization, the table will automatically send an ajax request, then render the data, which is not what I want !:(
You should use "iDeferLoading" : 0 in DataTables parameters, when you initialize it:
var table = $("#table").dataTable({
"bProcessing": true,
"bServerSide": true,
"iDeferLoading": 0,
"sAjaxSource": service_url,
"sServerMethod": "POST",
...
...
(or "deferLoading":0 for newer DataTables versions, 1.10 and above),
and then add the event to your button:
$("#button").on("click", function (event) {
$('#table').dataTable().fnDraw();
});
https://datatables.net/examples/server_side/defer_loading.html
in a similar situation, this is how I did it.
<script>
$(function ($) {
$("#tbl").DataTable({columns:[{data:"id"}, {data:"text"}], dom: "tB", buttons: [{ text: "Load Me", action: function (e, dt, node, config) { loadme(e, dt, node, config); } }] });
}
);
// // parameters are passed from the datatable button event handler
function loadme(e, dt, node, config) {
parms = JSON.stringify({ parm1: "one", parm2: "two" });
$.ajax({
// my test web server that returns an array of {id:"code field", text:"country namee"}
url: "WebService1.asmx/GetAList",
data: JSON.stringify({ s: parms }),
type: 'post',
contentType: "application/json; charset=utf-8",
dataType: "json",
// this is just away of passing arguments to the success handler
context:{dt:dt, node:node},
success: function (data, status) {
var contries = JSON.parse(data.d);
for (var i = 0; i < contries.length; i++){
this.dt.row.add(contries[i], "id", "text");
this.dt.draw();
}
},
error: function (one, two) {
debugger;
}
});
}
</script>
</head>
<body>
<div style="width:500px">
<table id="tbl">
<thead>
<tr>
<th>Code</th>
<th>Contru</th>
</tr>
</thead>
<tbody></tbody>
<tfoot></tfoot>
</table>
</div>
</body>
After looking at the source code for half a day, I finally found a solution. First I needed a custom parameter called firstAjax and set it to false. like this:
$("#example").DataTable({
serverSide: true,
ajax: {
url: 'your url'
},
firstAjax: false
});
Then I changed the
_fnReDraw (settings); //in datatables.js line 4717
to
if (settings.oInit.firstAjax) {
_ fnReDraw (settings);
}
If the compressed js file(datatables.min.js), you should find _fnReDraw function corresponding alias.
I found the solution, in the initialization make like this, with the "oLanguage":
$('.table').dataTable({
oLanguage: {
sUrl: ""
}
});
After initialize datatables with ajax, use this simple line to call ajax for get data:
$('#table').DataTable().ajax.reload();
this code may not working with old versions of datatables.
Download latest version: https://datatables.net/download