How to refresh Datatable data from js array of objects - javascript

I'm using the jquery DataTables plugin to display an array of objects. I would like to clear the table and redraw using the changed data. However, the only way I've been able to do that so far is to destroy the table and reinitialize. I'd like to know if there is a simple way to refresh from JS data source. This is what I'm doing, it works but feels wrong...
if (NAMESPACE.table){
NAMESPACE.table.destroy();
}
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
]
});

if you want to clear the data present in dataTable simply call table.clear() it clears all cells in table.
and then add new data using table.row.add().draw();
table.destroy() does not removes data present in cell of table, it only destroys the current instance of dataTable you created.

Make it simpler:
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
],
"destroy": true
});

Related

How can I add Id to row with jquery ajax server-side

I need to add id property to TR of table data dynamically added with jquery ajax server-side and write data there. how can I do that. I add the Json data coming with the code below to the lines.
"ajax": {
"url": '/Siparis/SiparisleriDoldur/',
"type": 'POST',
"dataType": 'json',
"data": { liste }
},
"columns":
[
{ "data": "MusteriAdi", "name": "Müşteri Adı" },
{ "data": "MalzemeAdi", "name": " Ürün Adı" },
{ "data": "SiparisAdet", "name": "Sipariş Adedi" },
],
i want to do;
<tr id='IdNumber' data-id='IdNumber'>
<td>bla</td>
<td>bla</td>
<td>bla</td>
</tr>
Note: IdNumber is in data(json list)
Given your use of the Datatable library you can use the createdRow property of the settings to amend each row as required. Try this:
$('#yourDatatable').dataTable({
"createdRow": function(row, data, dataIndex) {
let id = data[0]; // amend 'data[0]' here to be the correct column for your dataset
$(row).prop('id', id).data('id', id);
},
"ajax": {
// ...
},
// other settings as normal...
});
I fixed my problem with;
"createdRow": function (row, data) {
var id = data.Id;
$(row).prop('id', id).data('id', id);
$(row).attr('data-id', id).data('data-id', id);
},

Populate a datatable starting from the second column

I have a datatable that retrieves json data from an api. The first column of the table should only contain a checkbox. However, when retrieving the data it populates the first column as well.
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
$('#parametrictable').DataTable({
data : json.data,
columns : json.columns,
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
})
});
Is there any way that I can set that the data should only populate starting from the second column, leaving the first column to only contain the checkbox?
You can fix this issue by updating the api or in your js code just updating the data key value to null for first object in the json.columns array like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
json.columns[0].data = null;
json.columns[0].defaultContent = '';
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
.... your rest of code
})
});
EDIT:
I meant what your suggestion only did was hide the data that was overlapping with the checkbox. I don't want it hidden. I want the first column to be, by default, only checkboxes. and the overlapping data should be on the 2nd column.
You can update your API like this to achieve that:
"columns": [
{
"data": null,
"defaultContent": ""
},
{
"data": "DT_RowId",
"title": "Id"
},
{
"data": "supplier",
"title": "supplier"
},
{
"data": "color",
"title": "color"
}
],
Or, you can update your code without modifying your API like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
// Add object for checkbox at first position
json.columns.unshift({"data": null, "defaultContent": ""});
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
....your rest of code
})
});

Datatable send current page number

I've been try to send current page number to server by overwrite a variable called pgno
here is my code :
function fill_datatable(status='',pgno='')
{
var pgno = 0;
table = $('.tb_scoin_available').DataTable({
"processing": true,
"serverSide": true,
"ordering" : false,
"infoCallback": function( settings, start, end, max, total, pre ) {
var api = this.api();
var pageInfo = api.page.info();
pgno = pageInfo.page+1;
return pgno;
},
"ajax":{
"url": base_url+'/adminPath/management_scoin/ajaxGetScoinAvailable',
"type": "POST",
"data":{ _token: csrf_token, status : status,pgno : pgno}
},
"columnDefs": [ { orderable: false} ],
"columns": [
{ "data": "no" },
{ "data": "created_at" },
{ "data": "serial_scoin" },
{ "data": "unit_scoin" },
{ "data": "unit_scoin_desc" },
{ "data": "unit_scoin_sc" },
{ "data": "unit_scoin_idr" },
],
});
}
when I try to alert on infoCallback :
alert(pgno) the variable already overwrited, but when I try to dump the request on backend the pgno POST give me null result like this :
Anyone can help me out ?
You can get the table page with the page() function, no need for the whole "page.info". It's better explained in Datatable's API: https://datatables.net/reference/api/page()
The method you're trying to access is only to get the information, not to set it. That is probably why it isn't working. Check their docs for better understanding of their API: https://datatables.net/reference/api/page.info()
EDIT:
You can get the current page through a simple calculation. Since you're using serverSide processing, you already have start and length. You just need to do start/length + 1 and you will get the current page number.

Jquery datatables does not display the column headers

This is linked to the question here. However, my case is a bit different. I would like to implement the same datatables example from the other question which is here. As you can see you have to pass the column names to be able to initialize the table headers like below
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
The problem is that I would not know the header names beforehand as they will change. I've tried initializing the column names when I get the data from ajax like below using a 3rd variable (see where it says 'pay attention to this line' but this doesn't work.
//PAY ATTENTION TO THIS LINE
var columnsHeaders = [];
var ab = $('#dynamicScenarioTable').DataTable({
"bDestroy": true,
"dom": 'T<"clear">lfrtip',
"ajax": {
"type": "POST",
"url": "dynamicScenario.htm",
"data": tags,
"dataType": "json",
"dataSrc": function(json){
//PAY ATTENTION TO THIS LINE
columnsHeaders.push({"data": json.header });
return json.vals;
},
"error": function(exception)
{
displayMessageOnError();
}
},
//PAY ATTENTION TO THIS LINE
"columns": [columnsHeaders],
tableTools: tableDefaultS.tableTools
});
Any ideas?
You can add a data-source attribute to the TH tags that are built on your table header. You can then have jQuery read those and construct the array to send into the DataTable constructor.
<tr>
<th data-source="name">Name</th>
<th data-source="position">Postion</th>
<th data-source="start_date">Start Date</th>
</tr>
Then in your JavaScript do something like this to construct the array
var columnsHeaders = [];
$("#dynamicScenarioTable thead th").each(function() {
colmnsHeaders.push(
{
data : $(this).data("source")
}
);
});
// construct your DataTable after this

jQuery DataTables default column value

I am trying to include an invisible column in a jQuery DataTable that can be set to default true in place of a null or undefined encountered in the data source.
Say I am working with a 6-columns DataTable. The first 5 columns are visible. The 6th column is set to not be visible. And it must contain either a true or false, regardless of whether the data source object has the corresponding key. In the column definitions for the DataTable, I tried this but it did not work.
{ "defaultContent": true, "data": "existing", "visible": false }
According to the API, I think defaultContent works only when data is null. Maybe that's why it does not work. I have provided the HTML, JS data and JS code for initializing the DataTable. Notice that once the DataTable is loaded and rendered, I dynamically append a row and re-draw. The data for this row contains the 6th column property and that is gets set just fine.
HTML:
<div id="demo">
</div>
JavaScript (data initialization):
var dataSet = [
{'engine':'Webkit','browser':'Safari 1.2','platform':'OSX.3','version':'125.5','grade':'A'},
{'engine':'Other browsers','browser':'All others','platform':'-','version':'-','grade':'U'}
];
JavaScript (DataTable creation and initialization):
$('#demo').html('<table class="display" id="example"></table>');
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "sortable" : false, "data": null, "defaultContent": "<button>Select</button>", "title" : "Choose"
},
{ "title": "Engine", "data": "engine" },
{ "title": "Browser", "data": "browser" },
{ "title": "Platform", "data": "platform" },
{ "title": "Version", "data": "version", "class": "center" },
{ "title": "Grade", "data": "grade", "class": "center" },
{ "defaultContent": true, "data": "existing", "visible": false }
],
initComplete: function(oSettings, json) {
console.log('drawing complete');
if (oSettings.fnRecordsTotal() > 1) {
$('#example').DataTable().row.add({
'engine' : 'Presto',
'browser' : 'Opera 7.5',
'platform' : 'Win 95+ / OSX.2+',
'version' : '-',
'grade' : 'A',
'existing' : false
}).draw();
}
}
} );
Here is the JSFiddle for the above example. If you click on the Select button in the first two rows, it returns undefined. The Select button on the third row yields false. I want the first two rows' Select button to yield true.
How do I set a default value for the 6th (invisible) column if no key/value is provided in the data-set object?
It returns undefined because existing not exists in dataSet. dataSet is static, defaultContent does not populate its value to the original dataSet. What you really want is the value of the hidden column, which will contain either defaultContent or dynamically added existing values.
var row = $('#example').DataTable().row( $(this).parents('tr') ),
index = row.index(),
data = row.cell(index, 6).data();
alert(data);
will return true, true and false. Forked fiddle -> http://jsfiddle.net/vsx7uxnf/

Categories