HTML DataTables render a function in the cell - javascript

I have a JavaScript function that creates the DataTable. For the first cell in each row, I want to render a vizualisation function (with 3Dmol.js library) and display the object in this cell. The 3Dmol.js requires a container where the function result should be placed (the element variable). I want to choose the current cell. I tried with $(this); but I get an error saying: "Uncaught error creating viewer: TypeError: div.getBoundingClientRect is not a function"
<script type="text/javascript">
var in_json = '{{ in_json }}'
$(document).ready(function () {
$('#fragmenterTable').DataTable({
'ajax': { url: in_json, dataSrc: 'data' },
"scrollX": true,
"scrollY": 200,
"autoWidth": false,
"columnDefs": [
{
"render": function ( data, type, row ) {
return function viz_frag(data) {
var glviewer = null;
data = data
let element = $(this);
glviewer = $3Dmol.createViewer(element, "gldiv");
glviewer.addModel(data,'mol2');
glviewer.setStyle({},{stick:{}});
glviewer.zoomTo()
glviewer.zoom(2,1000);
glviewer.render();
glviewer.setBackgroundColor(0xffffff);
};
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
});
$('.dataTables_length').addClass('bs-select');
});
</script>
What am I missing? Thank you!

Related

Trying to access dataTable variable outside ajax is giving undefined

I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.
I'm doing the same as in this example, only difference is the data is coming from an Ajax request.
Can you please help me understand why is that happening?
$(document).ready(function() {
var campId;
var t_OmnitureCode;
// Campaign input autocomplete
$("#campaign").autocomplete({
source: function(request, response) {
$.ajax({
url: "promotion",
type: "GET",
data: {
term: request.term,
action: "searchCampaign"
},
dataType: "json",
success: function(data) {
if (!data.length) {
var result = [{
label: "no match found",
value: "-1"
}];
response(result);
} else {
response($.map(data, function(item) {
return {
label: item.name,
value: item.campaignId
}
}));
}
}
});
},
select: function(event, ui) {
event.preventDefault();
campId = ui.item.value;
if (campId != "-1") {
this.value = ui.item.label;
// This will apply datatables getting the content from an Ajax call
t_OmnitureCode = applyDataTableOmnitureCode(campId);
}
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
// Handling form submission
$("#frm_promotion").on("submit", function(e) {
var form = this;
// Variable for datatable "t_OmnitureCode" is undefined below
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.
Here is the applyDataTableOmnitureCode code:
function applyDataTableOmnitureCode(campId) {
$("#tbl_omnitureCode").DataTable({
destroy: true,
scrollX: true,
fixedColumns: {
leftColumns: 1
},
"ajax": {
"url": "promotion",
"type": "GET",
"data": {
action: "searchOmnitureCodesByCampaignId",
campaignId: campId
},
"dataSrc": ""
},
"columns": [
{ "data": "key" },
{ "data": "omnitureCode" },
{ "data": "urlAppName" },
{ "data": "language" },
{ "data": "channel" },
{ "data": "createDateTime", "defaultContent": "" },
{ "data": "updateDateTime", "defaultContent": "" }
],
"columnDefs": [
{ "targets": 0, "checkboxes": { "selectRow": true } }
],
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"fnInitComplete": function() {
$("#omnitureCodeSection").show();
}
});
};
You may need to grab your DataTables object into a variable before using that:
var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).
You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.
It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :
var table;
$(document).ready(function() {
table = $('#example').DataTable({
...
});

IF else like at datatable jquery

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.

How to change jquery datatable value by dropdown value change

I am using jquery datatable to display table data based on dropdown list value, I am using ajax to get data from the table.
The problem is when the table first loads it is working fine but when I click on sort or search it displays processing which does not change until i refresh the page,the code is given below:
$( document ).ready(function() {
var table = $('#example').DataTable({
//"bProcessing": true,
//"sAjaxSource": "response.php",
"processing": true,
"serverSide": true,
//"bDestroy": true,
// "bJQueryUI": true,
"aoColumns": [
{ mData: 'FNAME' } ,
{ mData: 'FPRICE' },
{ mData: 'IMGPATH' },
{ mData: 'FDESC' },
{ mData: 'CID' }
],
"ajax": {
'type': 'POST',
'url': 'response.php',
'data': {id: $('#myselect').val()}
// "success":function (res) {
//
// }
}
});
$('#myselect').change(function() {
var item = $(this).val();
// alert(item)
var urld = 'response.php/'+item;
table.ajax.url(urld).load();
table.reload();
});
// setInterval( function () {
// table.ajax.reload();
// }, 10000 );
//table.fnDraw();
});
If you are using serverside processing check this out for custom sort https://datatables.net/forums/discussion/9857/server-side-processing-custom-sort-solution-like-formatted-num-sorting-plug-in

Sorting on a column in removing html contents in Datatables 1.10

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...
}
} );
} );

How to refresh datatable list jquery?

I am using DataTable Jquery for bind list of records. I face below issue.
I am using jquery model popup for addnew and update record in MVC 4.0 Razor with no submit button only using ajax function. When I am click on "save" button and I want to update list with latest changes, but it can not. My code as below.
For Index page for list bind.
<script type="text/javascript">
$(document).ready(function () {
if (fnServerObjectToArray) {
var oTable = $('.datatable').dataTable({
"bJQueryUI": true,
"sScrollX": "",
"bSortClasses": false,
"aaSorting": [[0, 'asc']],
"bAutoWidth": true,
"bInfo": true,
"sScrollY": "100%",
"sScrollX": "100%",
"bScrollCollapse": true,
"sPaginationType": "full_numbers",
"bRetrieve": true,
"bProcessing": true,
"sAjaxSource": $('.datatable').attr('data'),
"aoColumns": [
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' },
{ bSortable: false }
],
"fnServerData": fnServerObjectToArray()
});
}
});
fnServerObjectToArray = function () {
return function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": function (json) {
var a = [];
for (var i = 0, iLen = json.aaData.length; i < iLen; i++) {
var inner = [];
inner.push(json.aaData[i].Name);
inner.push(json.aaData[i].Price);
inner.push(json.aaData[i].Phone);
inner.push(json.aaData[i].Email);
inner.push("<a title='Edit Place' class='EditDialogPlacesToStay' href='/placetostay/" + json.aaData[i].Id + "/edit'><img src='/Content/images/icons/small/grey/pencil.png' title='Edit' /></a> <a class='DeleteConfirm' href='/placetostay/" + json.aaData[i].ID + "/delete'><img src='/Content/images/icons/small/grey/trashcan.png' title='Delete' /></a>");
a.push(inner);
}
json.aaData = a;
fnCallback(json);
},
"error": function (error) {
}
});
}
}
</script>
On save button in success function I call the location.reload().
But I could not bind the latest changes of records means List is not refreshed.
Please help me for same.
Wrap the datatable initialization into a function, like initDataTable(), and add the option bDestroy to the settings :
function initDataTable() {
if (fnServerObjectToArray) {
var oTable = $('.datatable').dataTable({
"bDestroy" : true, //<-- add this option
"bJQueryUI" : true,
...
//anything as above
});
}
}
$(document).ready(function () {
initDataTable();
});
when you want to refresh / reload, like by a click on a button :
<button id="refresh">Refresh</button>
$("#refresh").click(function() {
initDataTable();
});
here is a demo -> http://jsfiddle.net/cxe5L/
To avoid the cache-issue
jQuery dataTables has hardcoded cache : true into its AJAX-calls. You have "sAjaxSource": $('.datatable').attr('data'). I assume data holds the path to an external resource, like /data/getdata.asp or similar? Add a timestamp as param to that resource, like
sAjaxSource : $('.datatable').attr('data')+'?param='+new Date().getTime()
so the sAjaxSource becomes on the form
/data/getdata.asp?param=1401278688565
This is basically the same thing jQuery is doing, when cache : false is set on a AJAX-request.
location.reload() will refresh the page content and your
$(document).ready(function () {}
is executing again instead of getting the latest changes. Check weather your database has new records or not.

Categories

Resources