How to load extra Javascript in Datatable Server Side processing? - javascript

I am using Datatable.net 1.10, with server processing. It is all good and working fine, but I can't get other javascript to work in the datatable. For example I was using tippy.js to generate nice tooltip in the table. This was working fine with client-side processing but javascript is totally ignored while using server-side processing.
Here is the Javascript I am using for the datatable (shortenened a bit):
function myDataTableAjax_Accident(id, actionURL) {
var areaDDL = document.getElementById('_AreaDDl');
var areaID = areaDDL.options[areaDDL.selectedIndex].value;
var incidentStatusDDL = document.getElementById('_IncidentStatus');
var incidentStatusID = incidentStatusDDL.options[incidentStatusDDL.selectedIndex].value;
var incidentKind = document.getElementById('incidentKind').value;
$('#' + id).DataTable({
dom: //cut for shortness
, serverSide: true
, processing: true
, pageLength: 100
, deferRender: true
, ajax: {
url: actionURL,
type: 'POST',
contentType: "application/json",
data: function (model) {
return JSON.stringify(model);
},
},
columns: [
{ data: null, defaultContent: "" },
{ data: "incident_EHSconnect_ID" },
{
data: "accident_type_name", defaultContent: defaultValueTxt
},
{ data: "incident_category", defaultContent: "" },
{ data: "incident_area_name", defaultContent: "" },
{ data: "location", defaultContent: defaultValueTxt },
{ data: "incident_description", defaultContent: "" },
{
data: null,
defaultContent: "",
orderable: false,
render: function (data, type, row, meta) {
var btns =
'<button id="' + data.incident_ID + '" data-id="' + data.incident_ID + '" class="modalDetails btn btn-default btn-control col-md-6 tip" title="Shows details of the accident" ><span class="glyphicon glyphicon-modal-window "></span> Details</button>' +
'<span class="glyphicon glyphicon-edit"></span> Edit ' +
'<span class="glyphicon glyphicon-download"></span> PDF'
;
if (!data.signed_by_injured_party) {
btns += '<span class="glyphicon glyphicon-pencil"></span> Sign';
}
return btns;
}
},
],
columnDefs: [{
className: 'control',
orderable: false,
targets: 0
}],
});
}
And here is the view:
#using AspMvcUtils
#using EHS.Utils
<table class="table table-bordered tblAccident" style="margin-top: 0px !important; width: 100%;" id="tblAccident">
<thead class="scrollStyle">
<tr>
<th></th>
<th>ID</th>
<th>Type</th>
<th>Category</th>
<th>Location</th>
<th>Exact Location</th>
<th>Description</th>
<th>Reported by</th>
<th>Reported Date</th>#*6*#
<th>Incident status</th>
<th data-priority="-1" class="col-md-6" style="max-width:150px;">Controls</th>
</tr>
</thead>
#*Rows -------------------------------------------------------------------------------------------------------*#
<tbody class="scrollStyle"> </tbody>
</table>
<div id="modalContainer" class="col-lg-12 col-md-12 col-sm-12 col-xs-12"></div>
<script>
tooltip('.tip', 'ehs');
$(document).ready(function () {
myDataTableAjax_Accident('tblAccident', '#Url.Action("DatatableServerSideIndex")');
});
</script>
And here is the tooltip function:
function tooltip(selector, userTheme) {
tippy(selector, {
theme: userTheme,
position: 'right',
animation: 'scale',
duration: 600
})
}
(I am using ASP.NET MVC4 by the way).
How can I get the extra javascript to work properly in the table?

You have to call tooltip after datatables complete its initialization, you can use fnInitComplete callback to do that:
$(document).ready( function() {
$('#example').dataTable({
...,
"fnInitComplete": function(oSettings, json) {
alert( 'DataTables has finished its initialisation.' );
// call tooltip here
tooltip('.tip', 'ehs');
}
});
});
Because you are using datatables and tooltip in 2 separate functions you can use callbacks to call them in order:
myDataTableAjax_Accident function:
function myDataTableAjax_Accident(id, actionURL, done) {
...,
"fnInitComplete": function(oSettings, json) {
done();
}
}
And then in your View you can pass done parameter as a function and then call tooltip like this:
<script>
$(document).ready(function () {
myDataTableAjax_Accident('tblAccident', '#Url.Action("DatatableServerSideIndex")', function() {
tooltip('.tip', 'ehs');
});
});
</script>

Related

DataTables sorting for category name column doesn't work

Here is HTML code
<table id="datatable-language" class="table table-hover datatable-highlight">
<thead>
<tr>
<th></th>
<th>image</th>
<th>category_name</th>
<th>status</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
Here is the JS code inside Datatable
columns: [
{
title: `<input type="checkbox" class="styled" onchange='toggleSelectAll(this);'>`,
orderable: false,
data: "category_id",
width: "50px"
},
{
data: "image",
render: function (data, type, row) {
return `<img src="${row['image']}" height="50px">`;
},
width: "100px"
},
{
data: "name",
ordering: true,
render: function (data, type, row) {
return `${row['name']}`;
}
},
{
data: "cstatus",
width: "30px"
},
{
width: "30px",
data: "category_id"
},
{
width: "10px",
data: "category_id"
},
],
columnDefs: [
{
targets: 1,
orderable: true
},
{
targets: 2,
orderable: true
},
{
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
targets: 3,
render: function (data, type, row) {
var status = (data == "1" ? 'checked="checked"' : '');
return statusSwitch(row.category_id, status);
}
},
{
targets: 4,
orderable: false,
selectable: false,
visible: true,
render: function (data, type, row) {
return `<a data-popup="tooltip" title="${locales['text_preview']}" target="_blank" href="{{ linkfront('product/category', 'path=') }}${row['category_id']}" class='text-default'><i class='fa fa-eye fa-lg valign-middle'></i></a>`;
}
},
{
targets: 5,
orderable: false,
render: function (data, type, row) {
return `<ul class="icons-list pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-menu9"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href='{{ link('catalog/category/update') }}?category_id=${row['category_id']}'><i class='icon-pencil7'></i> ${locales['button_edit']}</a></li>
<li><a onclick="removeItem(${row['category_id']})"><i class='icon-trash'></i> ${locales['button_delete']}</a></li>
</ul>
</li>
</ul>
`;
}
}
]
As you see, I make the orderable attr to true and the category_name still not working. Is there's a missing property of config?!
so what is the problem? the rest of the code doesn't make sense at all. I attached the snippets that make the table configurations
{
data: "name",
ordering: true,
render: function (data, type, row) {
return `${row['name']};
}
you write this
change data:"name" to data:"category_name"
and also return
${row['name']};
here change name to category_name
Take a look at the columns.render docs > https://datatables.net/reference/option/columns.render, especially the type param.
Your problem is that DT will sort the columns rendered markup, not the name value itself. So pass back the name value for sorting, markup for everything else:
render: function (data, type, row) {
return type == 'sort'
? row['name']
: `${row['name']};
}

Javascript date filter to DataTable using single textbox with calendar selection

Javascript Date filter to DataTable using single textbox with calendar selection.
Below is my datatable and script code.
<table id="datatable" class="table table-bordered table-striped dataTable" style="width: 100%">
<thead>
<tr>
<th style="width: 300px;">SDMSID</th>
<th style="width: 300px;">Asessor</th>
<th style="width: 300px;">Sector</th>
<th style="width: 300px;">Job Role</th>
<th style="width: 300px;">State</th>
<th style="width: 300px;">City</th>
<th style="width: 300px;">Assessment Date</th>
<th style="width: 300px;">Batch Status</th>
<th>Edit Assessor</th>
<th>Add Candidates</th>
<th>Manage Batch</th>
</tr>
</thead>
</table>
I used below script to fill data-table
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function loadgrid() {
$.ajax({
url: 'Getdropdowns.asmx/filreschedulebatchgrid',
method: 'post',
dataType: 'json',
success: function (data) {
$("#datatable").dataTable().fnDestroy()
$('#datatable').dataTable({
responsive: true,
paging: false,
sort: true,
searching: true,
processing: true,
destroy: true,
data: data,
aaSorting: [],
columns: [
{ 'data': 'SDMSId' },
{ 'data': 'UserName' },
{ 'data': 'SectorFullName' },
{ 'data': 'JobRoleFullName' },
{ 'data': 'State' },
{ 'data': 'City' },
{
'data': 'AssessmentStartDate',
'render': function (Assessment_Date) {
var date = new Date(Assessment_Date);
var month = date.getMonth() + 1;
return (month.length > 1 ? month : "0" + month) + "/" + date.getDate() + "/" + date.getFullYear();
}
},
{ 'data': 'DisplayName' },
{
'data': 'BatchId',
'sortable': false,
'searchable': false,
'render': function (BatchId) {
return '</i>';
}
},
{
'data': 'BatchId',
'sortable': false,
'searchable': false,
'render': function (BatchId) {
return '</i>';
//'<input id=' + BatchId + ' type="button" onserverclick="foo_OnClick" />';
}
},
{
'data': 'BatchId',
'sortable': false,
'searchable': false,
'render': function (BatchId) {
return '</i>';
}
}
]
});
}
});
};
});
I tried below example not working and i need some easy way to achieve this filter.
http://plnkr.co/edit/8z7cojpJoCSJXRn9prNj?p=preview
Please suggest how to achieve single data filter with calendar thank you in advance.
Based on the example you provided, to achieve a filter based on a date input you need to:
1) Include the date picker within your HTML:
<p id="date_filter">
<span id="date-label-from" class="date-label">From: </span><input class="date_range_filter date" type="text" id="datepicker_from" />
</p>
2) Include the following field within your datatable:
"sSearch": "Filter Data"
3) When creating your table, assign it to a variable, for example:
var oTable = $('#datatable').dataTable({
your code goes here...
});
4) Assign the datepicker functionality to your HTML input element:
$("#datepicker_from").datepicker({
showOn: "button",
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function() {
minDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
});
More information about Jquery's datepicker functionality can be found here:
http://api.jqueryui.com/datepicker/

ajax.reload not working second time

I am using datatables in mu MVC application, i want to refresh my table everytime i edit any record through model popup.
it works one repord only, when i open model popup second time to edit same / other records it doesn't.
please help, here is my code.
<div class="tablecontainer">
<table id="schoolsTable" class="table table-bordered table-condensed table-hover table-striped">
<thead>
<tr>
<th>
Status
</th>
<th>
Code
</th>
<th>
Name
</th>
<th>
Address
</th>
<th>
Actions
</th>
</tr>
</thead>
</table>
</div>
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/css/dataTables.bootstrap.min.css">
#section Scripts{
<script src="~/Content/datatables/datatables.min.js"></script>
<script src="assets/lib/jquery/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.26.6/js/jquery.tablesorter.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#schoolsTable').DataTable({
"ajax": {
"url": "/School/viewschool",
"type": "Get",
"datatype": "json"
},
"columns": [
{ "data": "Mas_SchoolStatusID", "autowidth": true },
{ "data": "SchoolCode", "autowidth": true },
{ "data": "SchoolName", "autowidth": true },
{ "data": "SchoolAddress", "autowidth": true },
{
"data": "Mas_SchoolID", "width": "50px", "render": function (data) {
return '<a class="popup" href=/School/Edit/' + data +'>Edit</a>';
}
}
]
});
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'))
})
function OpenPopup(pageUrl)
{
var $pageContent = $('<div/>');
$pageContent.load(pageUrl);
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
dragable: false,
autoOpen: false,
resizeable: false,
model: true,
title: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('distroy').remove();
}
})
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
oTable.ajax.reload();
$dialog.dialog('close');
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
});
</script>
}
i misspelled in destroy in close function as distroy.
close: function () {
$dialog.dialog('distroy').remove();
}
which should be:
close: function () {
$dialog.dialog('destroy').remove();
}

Calling href with Angular to open modal

Context
I´m working in this Tutorial, is about CRUD with DataTable, but difference I´m using Asp.Net WebApi with Angular
I´m into step 9, where tutorial made partial views for pop-up window, but I don´t use partial view, instead it, I use Angular Views
Problem
I don´t know how to replace that partial View for my Angular View
Code
View
<table class="table table-striped table-hover table-bordered dt-bootstrap no-footer" id="tabla_catalogos" role="grid" aria-describedby="sample_editable_1_info">
<thead>
<tr>
<th class="hidden"></th>
<th style="width: 200px;"> Codigo </th>
<th> Nombre </th>
</tr>
</thead>
<tbody></tbody>
</table>
JS
$('#tabla_catalogos')
.DataTable({
searching: true,
dom: 'ftpB',
autoWidth: false,
buttons: [
//'excelHtml5', 'csv', 'print'
],
paging: true,
select: {
style: 'single'
},
info: false,
ordering: true,
"processing": true,
ajax: {
method: 'GET',
url: "../../api/Catalogo/GetCatalogoRegistro/" + selected.ID,
dataSrc: '',
beforeSend: function(request) {
request.setRequestHeader("Version", $scope.usuario.Version);
request.setRequestHeader("Origen", 'Web');
}
},
columns: [
{ data: 'Catalogo', visible: false, searchable: false },
{ data: 'Codigo' },
{ data: 'ID', visible: false, searchable: false },
{ data: 'Nombre' },
{ data: 'Padre', visible: false, searchable: false },
{
data: 'ID',
render: function(data){
return '<a class="popup" href="root.detalleregistros'+data+'">Editar</a>';
}
},
{
data: 'ID',
render: function (data) {
return '<a class="popup" href="root.detalleregistros' + data + '">Eliminar</a>';
}
}
],
pageLength: 10 //,
//pagingType: "simple_numbers"
,
language: {
"emptyTable": "No se encontraron registros",
"zeroRecords": "No encontraron coincidencias",
"search": "Buscar: "
}
});
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
});
function OpenPopup(pageUrl) {
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable: false,
autoOpen: false,
resizable: false,
model: true,
title: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
};
Angular Service, invoke view:
.state('root.detalleregistros', {
url: "detalleRegistros.html",
templateUrl: "../SPA/administrador/catalogos/detalleRegistros.html",
controller: "detalleRegistrosCtrl",
authenticate: true
})
When I clic into url as mi code '<a class="popup" href="root.detalleregistros'+data+'">Editar</a>'; it redirect me to http://localhost:55720/admin/root.detalleregistros/1
instead
http://localhost:55718/admin/#/detalleRegistros.html
What I´am doing wrong there? help is very appreciated. Regards
I try '<a class="popup" ui-sref="root.detalleregistros({data:11})">Editar</a>'; as #Agam Banga comment but modal just don´t open, I need to add something to table view? or what can be wrong there?
You have defined the state for "root.detalleregistros". To Open this state, you need to use the inbuild directive of ui-router which is ui-sref.
<a ui-sref="root.detalleregistros">Editar</a>
Also, if you want to pass params, you can use
<a ui-sref="root.detalleregistros({data:11})">Editar</a>

Datatable showing wrong page numbers

Following is the HTML code:
<table id="myTable" class="dTable1 contentList table table-bordered" style="z-index: 2; ">
<thead id="tableHeader">
<tr id="headerRow">
<th>Time</th>
<th>Event</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I am initializing the table on popup open using below JavaScript code:
showHistory = function (contentID) {
debugger;
var auditRes;
//var oTable = $('#AuditListtable').dataTable();
//oTable.fnDestroy();
//alert("outside");
$('#AuditListtable').dataTable({
"sAjaxSource":SERVERURL?contentId=' + contentID,
"aoColumns": [
{ "mData": "AccessDate" },
{
"mData": "EventDescription",
"bSortable": false
},
{
"mData": "IPAddress",
"bSortable": false,
"mRender": function (data, type, row) {
debugger;
return '<td> <span title="' + data + '">Played By: ' + row.FirstName + ', IP Address: ' + data + '</span></td>';
}
}
],
"paging": true,
"sDom": '<"top"p<"clear">>rt',
"sPaginationType": "full_numbers",
"searching": false,
"bFilter": false,
"processing": true,
"bServerSide": true,
"order":true,
"sServerMethod": "POST",
"bAutoWidth": false,
"iDisplayLength": 8
});
$('#historyPopup').modal('show');
}
The data will be populated in pop up. Currently we are having total 9 records but pagination is showing as 5 pages. After clicking on another page, it displays previous record. Table is not refreshed.
You've enabled server-side processing with "bServerSide": true. Most likely your response is incorrect.
If you indeed want server-side processing, your response should be something like:
{
"sEcho": 1,
"iTotalRecords": 9,
"iTotalDisplayRecords": 9,
"aaData": [
// ... skipped ...
]
}
where sEcho should have the value of sEcho parameter from the request, iTotalRecords is number of all records before the filtering, and iTotalDisplayRecords is number of all records after the filtering.
See server-side processing for more information.

Categories