Getting 500 while adding data to datatables in javascript .net mvc - javascript

So i'm trying to add data to datatable, i'm relatively new to Web Applications, i'm more of a mobile app developer
I've looked into a few examples and i've come up with a solution to do it, but for some reason i'm getting this error on chrome
DataTables warning: table id=personaliseDatatable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
And if i check the console i'm getting Internal Server Error 500, but in fact the controller is getting triggered and i'm able to get the data from the repository, but its not able to return is what i'm able to understand
This is my method in controller
public JsonResult GetAllCapacityData()
{
try
{
var data = _capacityService.GetAllData(null).ToList();
return Json(new
{
data = data
});
}
catch (Exception ex)
{
_logger.Error("WebApp -> AreaMappingController -> GetAllData -> Catch -> ", ex);
throw;
}
}
and this is my ajax request
$(document).ready(function() {
if ($('#loaderDiv').hasClass("show")) {
$('#loaderDiv').removeClass("show");
}
GetCapacityData();
});
function GetCapacityData() {
$('#personaliseDatatable').DataTable({
responsive: true,
processing: false,
serverSide: false,
searching: true,
scrollX: true,
bDestroy: true,
"scrollX": true,
aaSorting: [0, 'desc'],
ajax: {
url: '#Url.Action("GetAllCapacityData", "Capacity")',
type: 'POST'
},
language: {
search: "",
searchPlaceholder: "Search...",
sInfoFiltered: ""
},
columns: [{
"render": function(data, type, full, meta) {
return meta.row + 1;
}
},
{
data: "data.ZoneMaster.ZoneName"
},
{
data: "CateogoryName"
},
{
data: "SubCateogoryName"
},
{
data: "ServiceType"
},
{
data: "UserType"
},
{
data: "Division"
},
{
data: "SlotName"
},
{
data: "AllowBooking"
},
{
data: "HoursBlockAhead"
},
{
data: "DaysOpenAheadForBooking"
},
{
data: "MaximumOrderCapacity"
},
{
mRender: function(data, type, row) {
return '<a class="actionLinks" data-toggle="tooltip" title="View Details" style="cursor:pointer;" onclick="EditCapacity(' + row.CapacityPlannerId + ')">Edit</a>';
},
sortable: false,
searchable: false
}
]
});
alert(data.ZoneMaster.ZoneId);
}
And this my Datatable
<div class="card-body">
<table style="width:100%" class="table table-striped table-hover table-bordered" id="personaliseDatatable">
<thead>
<tr>
<th>#</th>
<th>Zone</th>
<th>Cateogory</th>
<th>Sub Cateogory</th>
<th>Service Type</th>
<th>User Type</th>
<th>Division</th>
<th>Slot Name</th>
<th>Allow Booking</th>
<th>Hours to Block Ahead</th>
<th>Days Open Ahead</th>
<th>Max. Order Capacity</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Error on console
POST http://localhost:53201/Capacity/GetAllCapacityData 500 (Internal Server Error)
Any Help would be deeply appreciated

Related

Show an image in a "Jquery Datatable Plugin" cell using "columns.render" callback

I'm trying to display an image in a cell using the suggested answer from this post: Displaying image on Datatable.
However, the first parameter of the callback (data) should receive the string with the url pointing to the image, but it is always undefined.
This is how I initialize the datatable (columnDefs contains the callback I was talking about):
$().ready(function () {
var opt = {
columnDefs: [{
"targets": 2,
"data": 'teamLogo',
"render": function (data, type, row, meta) {
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
}
}],
info: false,
order: [[0, 'asc']],
paging: false,
responsive: true,
searching: false
};
$('#dataTable').DataTable(opt);
});
After an ajax call, I update data into the table, drawing it back again:
$('#cmbSeasons').change(function () {
var leagueId = parseInt($('#cmbLeagues').val().toString());
var seasonYear = parseInt($('#cmbSeasons').val().toString());
var settings = {
url: '/Standing/Read/Standings',
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: { leagueId: leagueId, seasonYear: seasonYear },
success: function (data) {
var t = $('#dataTable').DataTable();
t.clear();
for (var i = 0; i < data.length; i++) {
t.row.add([
data[i].rank,
data[i].teamName,
data[i].teamLogo,
data[i].points,
data[i].allPlayed,
data[i].allWin,
data[i].allDraw,
data[i].allLose,
data[i].allGoalsFor,
data[i].allGoalsAgainst,
data[i].homePlayed,
data[i].homeWin,
data[i].homeDraw,
data[i].homeLose,
data[i].homeGoalsFor,
data[i].homeGoalsAgainst,
data[i].awayPlayed,
data[i].awayWin,
data[i].awayDraw,
data[i].awayLose,
data[i].awayGoalsFor,
data[i].awayGoalsAgainst
]);
}
t.draw();
},
error: function (result) { alert('error ' + result.status + ': ' + result.responseText); }
};
$.ajax(settings);
});
The third column (data[i].teamLogo) contains the correct url I want to use as src for the image (I'm sure about it because I used the developer console to check the correctness of the string).
This is html Markup:
<table id="dataTable" class="text-center">
<thead class="text-capitalize">
<tr>
<th class="all">Rank</th>
<th class="all">Team</th>
<th class="all">Logo</th>
<th class="all">Pts</th>
<th class="all">Pl</th>
<th class="all">W</th>
<th class="all">D</th>
<th class="all">L</th>
<th class="all">GF</th>
<th class="all">GA</th>
<th class="all">HPl</th>
<th class="all">HW</th>
<th class="all">HD</th>
<th class="all">HL</th>
<th class="all">HGF</th>
<th class="all">HGA</th>
<th class="all">APl</th>
<th class="all">AW</th>
<th class="all">AD</th>
<th class="all">AL</th>
<th class="all">AGF</th>
<th class="all">AGA</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Is there anything wrong with the callback I wrote? Should be "data" parameter populated with a different string, instead of 'teamLogo'?
I'm using the latest version of datatables (1.10.20) and Jquery (3.5.1).
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
use an Img object to return instead
https://www.w3schools.com/jsref/dom_obj_image.asp
Changing the definition of the options this way:
$().ready(function () {
let opt: DataTables.Settings = {
columns: [
{ "data": "rank" },
{ "data": "teamName" },
{ "data": "teamLogo" },
{ "data": "points" },
{ "data": "allPlayed" },
{ "data": "allWin" },
{ "data": "allDraw" },
{ "data": "allLose" },
{ "data": "allGoalsFor" },
{ "data": "allGoalsAgainst" },
{ "data": "homePlayed" },
{ "data": "homeWin" },
{ "data": "homeDraw" },
{ "data": "homeLose" },
{ "data": "homeGoalsFor" },
{ "data": "homeGoalsAgainst" },
{ "data": "awayPlayed" },
{ "data": "awayWin" },
{ "data": "awayDraw" },
{ "data": "awayLose" },
{ "data": "awayGoalsFor" },
{ "data": "awayGoalsAgainst" }
],
columnDefs:
[{
"targets": 2,
"data": 'teamLogo',
"render": function (data, type, row, meta) {
return '<img src="' + data + '" alt="' + data + '"height="16" width="16"/>';
}
}],
info: false,
order: [[0, 'asc']],
paging: false,
responsive: true,
searching: false
}
$('#dataTable').DataTable(opt);
});
and simplifying the for loop like this:
t.rows.add( data ).draw();
did the trick!
It seemes that I had to define the data columns for the callback to work properly.

Datatable return [Object Object] on index column

I'm using datatable to show data from controller (i'm using Codeigniter) and need to show number column on the left table column.
I have tried:
$(document).ready(function() {
$('#booking_table').dataTable( {
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth : true,
ajax: {
"url" : base_url+"book/ajax_history",
"type" : "POST",
data : function (d){
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [
{
data : "b.booking_id",
visible : false,
},
{ data : null}, //where i should put index number
{ data : 'b.booking_date', className : "hidden-xs"},
{ data : 'b.from_name', className : "hidden-xs"},
{ data : 'b.to_name'},
],
responsive: false
});
// reference the table in a variable
var table = $('#booking_table').DataTable();
table.on( 'order.dt search.dt', function () {
table.column(0, {
search:'applied',
order:'applied'
}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
My Table:
<table class="table table-condensed" id="booking_table">
<thead>
<tr>
<th class="hidden-xs">id</th>
<th>No</th>
<th class="hidden-xs">
Tanggal
</th>
<th class="hidden-xs">
Pengirim
</th>
<th>
Penerima
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Refer to this https://www.datatables.net/examples/api/counter_columns.html
but, it's not working. What am I doing wrong ?
Please try below mentioned solution. Hope this will help you. Actually you initialized datatable two times.
$(document).ready(function() {
var table = $('#booking_table').dataTable({
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth: true,
ajax: {
"url": base_url + "book/ajax_history",
"type": "POST",
data: function(d) {
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [{
data: "b.booking_id",
visible: false,
},
{
data: null
}, //where i should put index number
{
data: 'b.booking_date',
className: "hidden-xs"
},
{
data: 'b.from_name',
className: "hidden-xs"
},
{
data: 'b.to_name'
},
],
responsive: false
});
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});

How to empty and refill jquery datatable?

I have a jquery datatable on my page. This datatable is gonna show data based on a request made to my api
The HTML that I have is like the following:
<table id="details" class="table table-bordered table-hover table-striped nowrap hidden display" cellspacing="0" width="100%">
<thead>
<tr>
<th> </th>
<th>Patient Full Name</th>
<th class="hidden">LF</th>
</tr>
</thead>
<tfoot>
<tr>
<th> </th>
<th>Patient Full Name</th>
<th class="hidden">LF</th>
</tr>
</tfoot>
<tbody>
<tr id="dummytr2"><td style="text-align:center;padding-top:20px;" colspan="7"><p><em>No Data Available</em></p></td></tr>
</tbody>
</table>
The first <th> is gonna be used to collapse the tr and get the facility (the third <th> or the hidden one) of this patient.
I have a dummy <tr> in the table because I don't want to initialize the datatable at the beginning so I don't get the error message that tells me that I can't initialize my datatable twice.
The request to my api is gonna be triggered through a bunch of buttons like the following:
$.ajax({
url: "https://" + window.myLocalVar + "/api/metrics/GetDetails?metricName=" + metric,
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function (requests) {
if (requests.length > 0) {
$("#dummytr2").remove();
for (var i = 0; i < requests.length; i++) {
var patient_name = requests[i].PatientFullName;
var lab_facility = requests[i].LabFacility;
tr = '<tr>\
<td class=" details-control"></td>\
<td>' + patient_name + '</td>\
<td class="hidden">' + lab_facility + '</td>\
</tr>';
$("#details > tbody").append(tr);
//click event for each tr
$('#details tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
}
}
// NOT SURE WHY IT IS NOT WORKING
$('#details').dataTable().fnDestroy();
var table = $('#details').DataTable({
"scrollX": true,
stateSave: true,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "PatientFullName" },
{ "data": "LabFacility" }
],
"order": [[1, 'asc']]
});
},
error: function (err) {
if (err) {
console.log(err);
}
}
});
});
function format(d) {
// `d` is the original data object for the row
var lf = d.LabFacility;
if (lf == "") {
lf = "No Lab Facility"
}
// wrapping text is not working???
return '<div class="table-responsive"><table class="table display" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Lab Facility:</td>' +
'<td>' + lf + '</td>' +
'</tr>' +
'</table></div>';
}
This ajax request is gonna get called each time a button is clicked. This means the content of my datatable is going to change each time a button was clicked. I tried to clear and refill it did not work.. I tried to destroy it .. it did not work.. each time I destroy my datatable and execute the script it won't change the content of the table.
I am not sure what's wrong with my code. My code works only for the first time.. the second time you click a button, it won't update my datatable.
Thanks!
You need to:
empty the table with empty()
remove $('#details').dataTable().fnDestroy();
add destroy: true option
For example:
if (requests.length > 0) {
// Empty table
$('#details').empty();
// ... skipped ...
var table = $('#details').DataTable({
destroy: true,
// ... skipped ...
});
// ... skipped ...
}
Please see sample of what I was saying in comments above:
var dataTable_ = null;
var init_ = false;
var initDataTable = function() {
dataTable_ = $('#table').DataTable({
preDrawCallback: function(settings) {
},
drawCallback: function(settings) {
if (init_ === false) {
init_ = true;
}
},
searching: true,
data: [],
fnCreatedRow: function(nRow, aData, iDataIndex) {
},
scrollY: true,
scrollX: true,
responsive: false,
serverSide: false,
autoWidth: false,
processing: false,
scrollCollapse: false,
lengthChange: false,
fixedColumns: false,
info: false,
select: {
info: false,
items: 'rows'
},
dom: '<"toolbar">Bfrtip',
orderMulti: false,
stripeClasses: ['dt-stripe-1', 'dt-stripe-2'],
columns: [{
name: 'test1',
data: 'test1',
title: 'Test1',
type: 'string',
orderable: true
},
{
name: 'test2',
data: 'test2',
title: 'Test2',
type: 'string',
orderable: true
},
]
});
};
var ajaxFunction = function() {
$.ajax({
url: "https://api.myjson.com/bins/7ed89",
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function(data) {
if (init_ === false) {
initDataTable();
}
if (typeof dataTable_ == 'object') {
dataTable_.rows().remove().draw();
dataTable_.rows.add(data);
dataTable_.draw();
}
//console.log(data);
}
});
};
$('#button').click(function() {
ajaxFunction();
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="table" class="cell-border hover call-list">
</table>
<button id="button">Click To Load Data</button>

DataTable ajax Nested Table with search

I have created jQuery DataTable with ajax which is working fine but I need to add another nested table inside it and it should be search from parent table. Is it possible !!
HTML
<table id="gatePass" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Company Name</th>
<th>From Date</th>
<th>To Date</th>
<th>Area</th>
<th>Status</th>
<!--<th style="display:none">itemId</th>-->
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript
var dataTableExample = 'undefined';
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
var a = "/_api/lists/getbytitle('GatePass')/items?$select=Id,Title,FromDate,ToDate,Area,OtherOldBuildingArea,OtherNewBuildingArea,WFStatus&$filter=WFStatus eq 'Approved'";
$.ajax({
url: a,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample = $("#gatePass").DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ mData: "Title" },
{
mData: "FromDate",
mRender: function (data, type, row) {
return moment(data).format('DD-MMM-YYYY hh:mm A');
}
},
{
mData: "ToDate",
mRender: function (data, type, row) {
return moment(data).format('DD-MMM-YYYY hh:mm A');
}
},
{ mData: "Area" },
{ mData: "WFStatus" },
]
});
}
function myErrHandler(data, errCode, errMessage) {
alert("Error: " + errMessage);
}
What is good for nested table to get data directly from ajax or to make dynamic string and to the table. Issue is if I make dynamic string than I think I cannot search on it. Please help me.

jQuery DataTables loads data from controller but does not display it

In short, I'm loading a list of clients (as JSON) from an MVC controller. I've verified that the data is structured properly, as well that it does get to the client. The only disconnect is that once the data is loaded, DataTables never displays it.
Here's the JavaScript that initializes the table. I'm almost positive it's configured correctly.
I use the dataSrc parameter to execute some extra code before the data is drawn. Note that it is being executed. I've stepped through just about every piece of this.
I also confirmed that $("clients table") finds the correct element.
$clientsTable = $("#clients table").DataTable({
deferRenderer: true,
info:true,
lengthChange: true,
lengthMenu: [25, 50, 75, 100],
processing: true,
saveState: true,
serverSide: true,
ajax: {
url: "LeadScatter/Clients",
type: "GET",
data: function (d) {
$.extend(d, { byPartner: $("#byPartner").val(), byEnabledDisabled: $("[name=byEnabledDisabled]:checked").val() });
},
dataSrc: function (data) {
getTabState("clients").isLoaded = true;
$("#clients .tab-content").fadeIn(_fadeTimeInMs);
$("#clients .dataTables_filter [type=search]").focus();
return data;
},
error: function (response) {
getTabState("clients").isLoaded = false;
selectedClient = undefined;
$("#tabs").tabs({ disabled: defaultDisabledTabs }).tabs("option", "active", 0);
updateSelectedClient();
showTabLoadError("clients", response.statusText);
if (response.status == 403) {
alert(response.statusText, response.status);
$("#clients").find(".dataTables_empty").text("Sorry, but you do not have permission to view Clients.");
}
}
},
columns: [
{ data: "cakeName", className: "button-cell client" },
{ data: "rpls", className: "number-cell" },
{ data: "forcePayoutIncrease", className: "number-cell" },
{ data: "allocation", className: "number-cell" },
{ data: "inMonthCap", className: "number-cell" },
{ data: "inMonthCapType", className: "number-cell" },
{ data: "toggle", className: "button-cell" },
{ data: "pushToDemo", className: "button-cell" }
]
});
Here's the object that DataTables is picking up. I removed extra array elements to save space. Trust that they're constructed correctly:
{
"draw": 1,
"recordsTotal": 784,
"recordsFiltered": 0,
"data": [
{
"id": 7689,
"cakeName": "<input type='radio' name='selected-client' value='7689' data-id='7689' data-cake-name='aa_test1' data-grouping-id='6666' id='selected-client-aa_test1' class='' /><label for='selected-client-aa_test1' class='disabled'>aa_test1</label>",
"rpls": 40,
"forcePayoutIncrease": 0,
"allocation": 0,
"inMonthCap": 0,
"inMonthCapType": "None",
"enabled": true,
"toggle": "<button type='button' class='button toggle' onclick='toggleClientEnabled(7689);'>Disable</button>",
"pushToDemo": "<button type='button' class='button' onclick='pushClientToDemo('aa_test1');'>Push To Demo</button>"
},
....
]
}
DataTables correctly updates the draw parameter with each subsequent request. Everything behind-the-scenes seems to work fine. Here's the HTML table where the data should be rendered:
<table border="1">
<thead>
<tr>
<th>CakeName</th>
<th>RPLS</th>
<th>ForcePayoutIncrease</th>
<th>Allocation</th>
<th>In-Month Cap</th>
<th>In-Month Cap Type</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
And finally, a screenshot of the table. It's initialized but no data is rendered. You can even see that it's getting the "recordsTotal" variable from the returned object and setting it in the footer.
Am I missing something obvious?
Well, this was frustrating to discover, but it turns out that the dataSrc function was causing it.
I missed in the documentation that when using that parameter as a function, you must return the collection of data that's being displayed, not the JSON object as a whole.
So this:
dataSrc: function (data) {
return data;
}
becomes this:
dataSrc: function (data) {
return data.data; //access the data variable from the returned JSON
}
Voila.

Categories

Resources