I'm trying to sort my table by adding data-order in createdCell callback - it's working fine but seems table cache is not updating after that - sorting by first column (date with timestamp in data-order) simply not working.
I have tried table.rows/cells().invalidate() - no effect.
$.ajax({
type: "POST",
url: getLayoutData().urls.get_validation_history,
data: {
build_pk: build_pk,
type: validation_type,
},
success: function(response){
var response_data = JSON.parse(response);
var table = $("#validationHistoryTable").DataTable({
data: response_data.snapshots,
destroy: true,
autoWidth: false,
columns: [
{data: 'updated'},
{data: 'updated_by'},
{data: 'type'},
{data: 'status'},
{data: 'comment'},
],
columnDefs: [
{"width": "30%", "targets": 4},
{"targets": 0,
"createdCell": function(td, cellData, rowData, row, col){
raw = $(td).text().split(" ");
date = raw[0].split(".");
iso_time = date[2]+'-'+date[1]+'-'+date[0]+' '+raw[1];
$(td).attr('data-order', Date.parse(iso_time).getTime());
}
}
],
You cannot insert orthogonal data by manipulating nodes. You can manipulate existing and recognized data-* values through nodes and invalidate(), but not as part of the post processing of DOM nodes. Look at https://datatables.net/manual/data/orthogonal-data. data-* values can be specified by
Markup
A render literal that points to an alternative JSON property
A render callback
See proof of concept in this little example -> http://jsfiddle.net/rtu0bjz6/
{
targets: 2,
createdCell: function(td, cellData, rowData, row, col){
counter++
$(td).attr('data-order', counter)
}
}
Does not have any effect. The column is sorted by its original data, not its data-order. However, if you are using a render() function and return a special value upon type "sort" then it works as expected.
{
targets: 3,
render: function ( data, type, row, meta ) {
return type == 'sort' ? meta.row : data
}
}
So in your case, you could do something like (not tested) :
{
targets: 0,
render: function ( data, type, row, meta ) {
if (type == 'sort') {
var raw = data.split(" ");
var date = raw[0].split(".");
var iso_time = date[2]+'-'+date[1]+'-'+date[0]+' '+raw[1];
return Date.parse(iso_time).getTime()
} else {
return data
}
}
}
Related
i have C# function That Return Me Json Formated Data , function is below
void DisplayProjectMasterList()
{
string JSONString = "";
DataTable Dt = DB.GetDataTable("Sp_GetProjectMasterList");
if (Dt.Rows.Count > 0)
{
JSONString = JsonConvert.SerializeObject(Dt);
}
Context.Response.Write(JSONString);
}
and I am Calling This Function Via Ajax .in console i am getting json data But i dont know how to pass it to Jquery data table to display.. below is the javascript function... please help Me
function DisplayProjectMasterList() {
$.ajax({
url: 'project-master.ashx',
type: "POST",
dataType: 'json',
data: {
'fun': 'DisplayProjectMasterList'
},
success: function (data) {
console.log(data);
if (Chk_Res(data.errorMessage) == false) {
$('#tbl').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
columns: [
{ 'data':data.Prj_Id },
{ 'data':data.Prj_No },
{ 'data':data.Prj_Name },
{ 'data':data.Cus_Company_Name },
{ 'data':data.Prj_StartDate },
{ 'data':data.Prj_CompletionDate },
]
});
}
}
});
}
i am Getting FOllowing error while doing So:
DataTables warning: table id=tbl - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Hi make sure the data you are being returned is in the following format:
{
"data": [
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
},
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
}
]
}
jquery Datatables by default looks for data property for the array of objects
https://datatables.net/reference/option/ajax.dataSrc
https://datatables.net/examples/ajax/objects.html
i'm pretty new using datatables and amaze with good fiture in datatables for handling a lots of data. i have read the documentation but still don't get the answer, too much example make me confuse which one is fit for my problem.
so, i trying to generated button which can edit value of selected row, but i think to complex for doing a button each row, i made it more simple with hyperlink text generated each button and can edit selected row which taken the ID of selected row.
The problem is when i succeed with generating link each row, the id of row is undefined.
on comment code name try 1, my table not showing and keep processing for long time
and comment code name try 2, my table working but when i hit edit the value is undefined.
here is my code :
$(document).ready(function(){
var dataTable = $('#empTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
var gender = $('#searchByGender').val();
var name = $('#searchByName').val();
data.searchByGender = gender;
data.searchByName = name;
}
},
'columns': [
{ data: 'id' },
{ data: 'nama' },
{ data: 'grade' },
{ data: 'dept' },
{ data: 'id' },
{ data: 'id',
render: function(data, type, row, meta)
{
//try 1 :
//var data = table.row( this ).data().id;
//return 'edit';
//try 2 :
//var i = row[0];
//return 'edit';
}
},
]
});
undefined ID Image, and
normally this should be ID ie:2200085 not undefined.
any help would be appreciated, sorry if the question just hit little scope but i think out there many people have same problem like me. Thankyou.
you are missing one step after columns[].
$(document).ready(function(){
var dataTable = $('#empTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
var gender = $('#searchByGender').val();
var name = $('#searchByName').val();
data.searchByGender = gender;
data.searchByName = name;
}
},
'columns': [
{ data: 'id' },
{ data: 'nama' },
{ data: 'grade' },
{ data: 'dept' },
{ data: 'id' },
{ data: 'id',
render: function(data, type, row, meta)
{
//try 1 :
//var data = table.row( this ).data().id;
//return 'edit';
//try 2 :
//var i = row[0];
//return 'edit';
}
},
],
createdRow: function ( row, data, index ) {
$(row).attr('title','Category ID : '+data[0]);
$(row).attr('id',data[0]);
$(row).click(function(){
alert(this.id+' is clicked');
});
}
});
How could I perform If else like method in datatable? The variable 'data' returns the value of the variable, which is correct, but if it is blank, it would return the word "from1", "from2" which is supposed to be the value of the variable "from1". Am I doing the right approach or do you have any suggestion as workaround in this problem? thank you for your answers. here is my code:
var table = $('#records').DataTable({
type: 'post',
"ajax": "getHumanTrainings",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [{
mData: 'tdesc'
}, {
data: "fdDateFrom2",
defaultContent: 'from1'
}, {
data: "fdDateTo2",
defaultContent: 'from2'
}, {
data: "fcTrainor2",
defaultContent: 'train1'
}, {
mData: 'dur'
}]
});
I'd use the render option for the column data that you have, its much more flexible in terms of wanting something to be displayed by default.
var table = $('#records').DataTable({
type: 'post',
"ajax": "getHumanTrainings",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [{
mData: 'tdesc'
}, {
data: "fdDateFrom2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for from1>]; // Just use the index for from1
}
// If not blank display data normally
return data;
}
}, {
data: "fdDateTo2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for from2>]; // Just use the index for from2
}
// If not blank display data normally
return data;
}
}, {
data: "fcTrainor2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for train1>]; // Just use the index for train1
}
// If not blank display data normally
return data;
}
}, {
mData: 'dur'
}]
});
I've left comments to give you a guide since I'm not familiar with your data, I would suggest printing out your row first over at render so you'd know which index to use.
I currently have a table that loads data from a REST API endpoint via AJAX:
$(document).ready(function() {
var table = $('#pendingTable').DataTable({
ajax: {
type: "GET",
url: url + '/rest/endpoint,
dataSrc: "_deployments"
},
columns: [
{ data: "service_name" },
{ data: "git_organization" },
{ data: "id" },
{ data: "timestamp" },
{ data: "username" },
{ data: "environment" },
{ data: "site" },
{ data: "status" }
],
fnCreatedRow: function( nRow, aData, iDataIndex ) {
$(nRow).attr('onclick', "openModal(" + aData["id"] + ")");
},
order: [
[2, 'sc']
]
});
$('.table-responsive').css('opacity', '0').fadeTo(500, 1, 'swing');
$('#pendingTable_filter input').attr("placeholder", "by User, Org & More");
});
I have been exploring the DataTables.net docs, but am having issues determining the best course of action for manipulating the "timestamp" data (i.e., format it into a proper date), prior to the table being drawn.
The API offers the ability to modify individual cells which I may be able to iterate through, columns, or both. How would I go about formatting this time-stamp? (the value is just a string representing milliseconds). Would I need to have some form of a callback, or should I manipulate the data after the table has already been drawn?
Any examples would be greatly appreciated. Apologies that I do not have any examples to offer of what I've tried, a majority of it has been pseudo-code that isn't doing what I thought it would.
This is how I've done it using render, which allows you to manipulate the data before it's displayed.
{ data: "id" },
{
'render': function (data, type, full, meta) {
var date = new Date(parseInt(data.substr(6), 0));
return ISODateString(date);
}
},
{ data: "username" },
I created a function called ISODateString that returns the date, month and year parts of the timestamp (obviously you can also return the time parts if necessary).
function ISODateString(d) {
function pad(n) { return n < 10 ? '0' + n : n }
return pad(d.getDate()) + '/' + pad(d.getMonth() + 1) + '/' + d.getFullYear();
}
I am unsing datatable 1.10, In my code in one of the column as per the requirement I am adding an HTML checkbox tag.
Now first time when the table gets rendered it shows me those checkboxes but when I click on that column to sort or any other column for sorting then the column which contains HTML contains are getting wiped out. (I crosschecked this with the chrome DOM inspector... the td element contains nothing :()
Below is my dataTable initialization code.
dataTableOptions: function() {
return {
"orderable": true,
"columnDefs": undefined,
"autoWidth": true,
"deferRender": true,
"data": undefined
};
},
dtRowGroupingOptions: function () {
return {
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: [""]
};
}
var dataTablesOptions = self.dataTableOptions();
dataTablesOptions.data = tableData;
dataTablesOptions["paginate"] = false;
dataTablesOptions["lengthChange"] = false;
dataTablesOptions["columnDefs"] = [{"targets": 0, "data": "serverName", 'title' : 'ServerName'},
{"targets": 1, "data": "COMMAND", 'title' : 'Command'},
{"targets": 2, "data": "PID", 'title' : 'Process Id'},
{"targets": 3, "data": "SIZE", 'title' : 'Size'},
{"targets": 4, "data": "USER", 'title' : 'User'},
{"targets": 5, "data": "action", 'title' : 'Actions', "type" : "html", "orderDataType": "dom-checkbox"}
];
dataTablesOptions["createdRow"] = function (nRow, aData, iDataIndex) {
var self = this;
if (aData["comments"] && aData["comments"].indexOf("Error") != -1) {
// Do not do anything
$('td:eq(0)', nRow).html(aData["serverName"]+"" +
"<a class='btn btn-danger' href='#' data-toggle='tooltip' title='Error in execution'><i class='icon-question'></i></a>");
}
return self;
};
var dcInfoDataTable = contentDiv.find('table.dcInfoTable').DataTable(dataTablesOptions);
I am also using datatables rowGrouping and searchhiglight plugin, below is the code.
// call row grouping
contentDiv.find('table.dcInfoTable').dataTable().rowGrouping(self.dtRowGroupingOptions());
// enable search highlighing
contentDiv.find('table.dcInfoTable').dataTable().fnSearchHighlighting();
Note: I tried removing rowGrouping plugin code just to make sure that this is not happeing because of this plugin but even after removing there is no effect, the HTML contents are getting wiped out.
Not only when you sort will it clear out your data, it will also clear it if you use any other feature that changes your table. This happens because each time the datatable draws for new data, it's clearing out your static data.
You need to re-append the checkboxes on each draw, you can do this in the fnDrawCallback event:
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
//append the checkbox to your table columns here...
}
} );
} );