ajax.reload not working second time - javascript

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

Related

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/

data-formatter to add hyperlink not working

I am trying to render a table in javascript as follows:
$('#serviceTable').DataTable({
responsive: true,
aaData: services,
bJQueryUI: true,
aoColumns: [
{ mData: 'service_name' },
{ mData: 'last_incident' },
{ mData: 'integration' }
]
});
I wanted a hyperlink on the text in column service_name. I tried adding data-formatter in the table definition as follows
<table id="serviceTable" class="table table-bordered table-striped">
<thead>
<tr>
<th data-field="service_name" data-formatter="LinkFormatter">Service</th>
<th data-field="last_incident">Last Incident</th>
<th data-field="integration">Integration</th>
</tr>
</thead>
</table>
and corresponding function
function LinkFormatter(value, row, index) {
return "<a href='/service/"+row.service_id+"'>"+value+"</a>";
}
But this does not add hyperlink. Can anyone please help?
Try using render like following.
$('#serviceTable').DataTable({
responsive: true,
aaData: service,
bJQueryUI: true,
aoColumns: [
{
mData: 'service_name' ,
"render": function(value, type, row, meta){
return "<a href='/service/"+row.service_id+"'>"+value+"</a>";
}
},
{ mData: 'last_incident' },
{ mData: 'integration' }
]
}
);
Working Sample
<head>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="serviceTable" class="table table-bordered table-striped">
<thead>
<tr>
<th data-field="service_name" data-formatter="LinkFormatter">Service</th>
<th data-field="last_incident">Last Incident</th>
<th data-field="integration">Integration</th>
</tr>
</thead>
</table>
</body>
<script>
var service=[{"service_id" :"1", "service_name":"Service 1","last_incident":"i1","integration":"i2"}
,{"service_id" :"2", "service_name":"Service 2","last_incident":"i1","integration":"i2"}
];
$('#serviceTable').DataTable({
responsive: true,
aaData: service,
bJQueryUI: true,
aoColumns: [
{
mData: 'service_name' ,
"render": function(value, type, row, meta){
return "<a href='/service/"+row.service_id+"'>"+value+"</a>";
}
},
{ mData: 'last_incident' },
{ mData: 'integration' }
]
});
</script>
have you tried DataTables render option?
DataTables Column Rendering
$('#serviceTable').DataTable({
responsive: true,
aaData: services,
bJQueryUI: true,
aoColumns: [
{ mData: 'service_name',
render: function(data, type, row) {
return ''+value+'';
}
},
{ mData: 'last_incident' },
{ mData: 'integration' }
],
});

How to load extra Javascript in Datatable Server Side processing?

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>

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>

Datatables server side adding column with parameter

I've a problem when using datatables serverside adding column with parameter. when create datatables serverside without additional column (just query list form database) it is works fine.
But i've difficulty when I want add one column that has value ID.
My script (JS) :
var dataTable = $('#mytablex').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"<?php echo base_url();?>admin/ap_invoice/getPOs", // json datasource
type: "post", // method , by default get
"data": {
"posupplier_id": $('#vendor_id').val()
},
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#mytablex").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
}
},
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<input type='checkbox' id='supid[]' name='supid[]'>"
} ]
} );
when i'm adding
<input type='checkbox' id='supid[]' name='supid[]'>
how to fill with value each rowid , i want become like this
<input type='checkbox' id='supid[]' name='supid[]' value='row->po_id'>
or you can use select ext.
$(document).ready(function () {
var events = $('#events');
var table = $('#example').DataTable({
//you can change data to ajax, there is an example
data: [{
"id": 1,
"name": "datatables",
"position": "anywhere",
"office": "stackoverflow",
"age": 18,
"salary": 341
}],
dom: 'Bfrtip',
columns: [
{
"data": "id"
},
{
"data": "name"
},
{
"data": "position"
},
{
"data": "office"
},
{
"data": "age"
},
{
"data": "salary"
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
}],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']],
buttons: [
{
text: 'Get selected data',
action: function () {
var count = table.rows({
selected: true
}).count();
events.prepend('<div>' + count + ' row(s) selected</div>');
var data = table.rows({
selected: true
}).data().toArray();
//print whole row data
console.log(data);
//print id
console.log(data[0].id);
}
}
]
});
});
#events {
margin-bottom: 1em;
padding: 1em;
background-color: #f6f6f6;
border: 1px solid #999;
border-radius: 3px;
height: 100px;
overflow: auto;
}
<link href="https://cdn.datatables.net/select/1.3.0/css/select.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Categories