Hi on my project i'm using jquery datatable. my question is i tried to load the table using ajax request but i failed. after several attempt please help me to get through this.
my datatable initializing was
var responsiveHelperDatatableColReorder = undefined;
$('#tbl_datasource').dataTable({
sDom: '<"top"i>rt<"bottom"flp><"clear">',
iDisplayLength: -1,
searching: false,
ordering: false,
scrollY: 300,
scrollX: true,
info: false,
paging: false,
"preDrawCallback": function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelperDatatableColReorder) {
responsiveHelperDatatableColReorder = new ResponsiveDatatablesHelper($('#tbl_datasource'), {
tablet: 1024,
phone: 480
});
}
},
"rowCallback": function (nRow) {
responsiveHelperDatatableColReorder.createExpandIcon(nRow);
},
"drawCallback": function (oSettings) {
responsiveHelperDatatableColReorder.respond();
},
ajax: {
url : '../Home/DataSourceHealth',
dataType: "json"
},
columns: [
{ "data": "providerName" },
{ "data": "fileName" },
{ "data": "status" },
{ "data": "lastRunTime" },
{ "data": "avgRecords" },
{ "data": "numberOfRecordes" },
{ "data": "numberOfErrorRecords" }
]
});
i use smartadmin admin template on my view
<table id="tbl_datasource" class="table table-striped table-hover table-condensed" width="100%">
<thead>
<tr>
<th data-class="expand">Name</th>
<th data-hide="phone,tablet">Source File</th>
<th data-hide="phone">Loading status</th>
<th data-hide="phone,tablet">Last run time</th>
<th data-hide="phone,tablet">Avg. records</th>
<th data-hide="phone,tablet">No.of records</th>
<th data-hide="phone,tablet">Deviation</th>
<th data-hide="phone,tablet">Data status</th>
<th data-hide="phone,tablet">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
on my controller i returned json object in this format
[
{
"loadDetailId": 108,
"loadDetailStatusId": 7,
"providerName": "Marin",
"status": "Complete File Process",
"fileName": "SiSenseChryslerPAPCanadaByClientAccount_03042015_bk8heq3q70.csv",
"numberOfRecordes": 633,
"avgRecords": 633.00,
"numberOfErrorRecords": 3,
"lastRunTime": "2015-03-10T15:01:40.14"
},
{
"loadDetailId": 109,
"loadDetailStatusId": 7,
"providerName": "Marin",
"status": "Complete File Process",
"fileName": "SiSenseCPAPDisplayCampaigns_03042015_nqh8w254o2.csv",
"numberOfRecordes": 100003,
"avgRecords": 100001.00,
"numberOfErrorRecords": 3,
"lastRunTime": "2015-03-10T15:01:42.283"
}
]
what was i missed when configuring jquery datatable?
updated
i have found the initial problem it was data structure should be like this
{
"data": [
{
"loadDetailId": 108,
"loadDetailStatusId": 7,
"providerName": "Marin",
"status": "Complete File Process",
"fileName": "SiSenseChryslerPAPCanadaByClientAccount_03042015_bk8heq3q70.csv",
"numberOfRecordes": 633,
"avgRecords": 633.00,
"numberOfErrorRecords": 3,
"lastRunTime": "2015-03-10T15:01:40.14"
},
{
"loadDetailId": 109,
"loadDetailStatusId": 7,
"providerName": "Marin",
"status": "Complete File Process",
"fileName": "SiSenseCPAPDisplayCampaigns_03042015_nqh8w254o2.csv",
"numberOfRecordes": 100003,
"avgRecords": 100001.00,
"numberOfErrorRecords": 3,
"lastRunTime": "2015-03-10T15:01:42.283"
}
]
}
but still having issue here is the firebug screenshot
thanks
You have a couple of things that could be going wrong here. First, if your returned JSON is not named data then you have to change your datatables initialization to add datasrc = "" property to it like so:
ajax: {
url : '../Home/DataSourceHealth',
dataType: "json",
dataSrc: ""
}
This makes datatables read in array of objects like the one that is returned in your case. Otherwise it looks for an object named data which when it doesn't find one, it assumes there is no data. Here is the documentation for this: https://datatables.net/reference/option/ajax.dataSrc
Second problem with your datatables is that you have more headers than the data that you're reading in through your columns:
9 headers:
<thead>
<tr>
<th data-class="expand">Name</th>
<th data-hide="phone,tablet">Source File</th>
<th data-hide="phone">Loading status</th>
<th data-hide="phone,tablet">Last run time</th>
<th data-hide="phone,tablet">Avg. records</th>
<th data-hide="phone,tablet">No.of records</th>
<th data-hide="phone,tablet">Deviation</th>
<th data-hide="phone,tablet">Data status</th>
<th data-hide="phone,tablet">Action</th>
</tr>
</thead>
7 data columns defined:
columns: [
{ "data": "providerName" },
{ "data": "fileName" },
{ "data": "status" },
{ "data": "lastRunTime" },
{ "data": "avgRecords" },
{ "data": "numberOfRecordes" },
{ "data": "numberOfErrorRecords" }
]
The number of headers and data columns needs to be exactly the same or it will not work.
try to debug with chrome or IE and look what error you get for your request.
Also try this
ajax: {
url : '/Home/DataSourceHealth',
dataType: "json"
},
Related
This is a frustrating problem for me, i have configured a table to use 5 column with the last column for buttons. However after the datatables finished rendering, it suddenly removed the last column from it.
This is the table:
<table id="grid-data" class="table table-striped dataTable" width="100%">
<thead>
<tr>
<th>Role Name</th>
<th>Activity Name</th>
<th>Start Date</th>
<th>End Date</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
This is the default view:
This is the datatables configuration:
$('#grid-data').DataTable({
"language": {
"emptyTable": '<i class="bi bi-table"></i><br>No Data Found',
"paginate": {
"previous": '<i class="fa fa-angle-left"></i>',
"next": '<i class="fa fa-angle-right"></i>',
},
"searchPlaceholder": 'Search',
"search": '<i class="bi bi-search"></i>',
},
'processing': true,
'serverSide': true,
'ordering': true,
'autoWidth': false,
'aLengthMenu': [[5, 10, 25, 50], [5, 10, 25, 50]],
'iDisplayLength': 5,
'ajax': {
'url': "../Master/GetList",
'type': "POST",
'data': function (data) {
//data.FilterGroup = $("#FilterGroup option:selected").val();
return data;
}
},
'columns': [
{ 'data': "roleName" },
{ 'data': "activityName" },
{
'data': "startDate",
'render': function (dt) {
return `<span>${moment(dt).format("DD/MM/YYYY")}</span>`
}
},
{
'data': "endDate",
'render': function (dt) {
return `<span>${moment(dt).format("DD/MM/YYYY")}</span>`
}
},
{
'data': null,
'render': function (dt) {
return `<i class="bi bi-pencil-square"></i>`
}
}
],
"columnDefs": [{
"targets": -1,
"visible": true,
}],
'initComplete': function (data) {
console.log(data.aoColumns)
console.log(data.aoColumns[4].sTitle)
}
});
This is the result after rendering:
See how the last column is missing? when i inspect it the last column was somehow removed from the html.
When trying to debug the cause, i find out that in the datatables data itself the column is still intact:
I've tried doing things like adding class all to the th element or setting individual width on the column but none of those worked.
What could be the cause for this?
I am trying to use a datatable and was wondering what i am doing wrong its just stuck on loading and showing waiting to start. This is on my activity controller and the LoadGridData function is called from the scripts below in my index.cshtml.
public ActionResult LoadGridData()
{
// Getting all Customer data
var data = GetAllActivityHeader();
return Json(new { data = data });
}
Here is my GetallActivityHeader function
public async Task<ActionResult<List<ActivityHeader>>> GetAllActivityHeader()
{
return await _activityRepo.GetAllActivityHeader();
}
This is my repositry method which is called above.
public async Task<List<ActivityHeader>> GetAllActivityHeader()
{
using (IDbConnection conn = Connection)
{
if(conn.State == ConnectionState.Closed)
conn.Open();
var result = await conn.QueryAsync<ActivityHeader>("GetActivityHeader");
return result.ToList();
}
}
In My Layout I have the following scripts
#section Scripts{
<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js">
</script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "/Activity/LoadGridData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name", "autoWidth": true },
{ "data": "Description", "autoWidth": true },
{ "data": "Phone", "autoWidth": true },
{ "data": "EmployeeName", "autoWidth": true },
{ "data": "SOP", "autoWidth": true },
{ "data": "Status", "autoWidth": true }
]
});
});
</script>
Html
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Phone</th>
<th>EmployeeName</th>
<th>SOP</th>
<th>Status</th>
</tr>
</thead>
</table>
</div>
But when i debug the code i am getting the following issue. Also for some reason my edit and delete buttons are not showing I persume i need to code those before they show. Is there any better components for working with datatables and asp.net core?.
And also here is what my view is showing
Edit 1
Ok so i made the method async and that worked and there data their but its still saying no data in the datatable
public async Task<ActionResult> LoadGridData()
{
// Getting all Customer data
var data = await GetAllActivityHeader();
return Json(new { data = data });
}
Finally this is my class obv I dont want to display all in the datatable so I just used the column headers i wanted or is that not how datatables work?.
I am trying to creating child rows in datatables by using json data. Some reason table and child rows are creating with data. So i don't understand the proble is.
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</div>
Javascript
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var data ={
"data": [ {
"name": "Michael Bruce",
"position": "Javascript Developer",
"salary": "$183,000",
"start_date": "2011/06/27",
"office": "Singapore",
"extn": "5384"
},
{
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
]
};
var table = $('#example').DataTable( {
"data":data,
"columns": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example 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');
}
} );
} );
Here is the datatables live for my code.
Your data variable is an object. it needs to be an array:
var data =
[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
....
];
vs
var data =
{ // remove
"data": // remove
[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
....
]}; // remove closing curly bracket
example: http://live.datatables.net/waburuz/10/edit
I am getting error in binding JSON data to constuct a data table.
My JSON is of the following:
[
{
"ID": 1,
"Number": "2",
"Name": "Avinash"
},
{
"ID":2,
"Number":"21",
"Name":"XYZ"
},
{
"ID": 3,
"Number": "20",
"Name": "KRR"
}
]
I am binding this to jquery datatable as below:
$(document).ready(function () {
$('#table_id').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": '<%:Url.Action("LoadData","Home")%>'
});
$('#table_id').css("width", "100%")
});
My Table Structure is as follows:
<table id="table_id" border="0" class="display" cellpadding="1" cellspacing="1" align="center">
<thead>
<tr>
<th>ID</th>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
</table>
I am getting error as follows:
Datatables Warning(tableid="table_id"):Requested Unknown Parameter'0' from the datasource for row 0
My Controller is as follows:
public ActionResult LoadData()
{
var Data = new DataTable();
Data=DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Data, Formatting.None);
return Json(new
{
aaData = JsonData
}, JsonRequestBehavior.AllowGet);
}
Please help..
I am trying to write some jquery code to retrieve a list of servers from a cloud account and display them in a table. When I load my page, my javascript executes and the proper JSON is returned, but when I try to use a jquery template to generate my html, I never get any output. Can anyone help me figure out where my problem is?
Javascript to fetch server data
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '../../api/server/getservers',
type: 'POST',
success: function (result) {
$('#serverTemplate').tmpl(result).appendTo('#serverTable');
},
});
});
</script>
Jquery Template Javascript
<script id="serverTemplate" type="text/x-jQuery-tmpl">
{{each servers}}
<tr>
<td>${status}</td>
<td>${name}</td>
</tr>
{{/each}}
</script>
HTML
<table>
<thead>
<tr>
<th>Status</th>
<th>Server Name</th>
</tr>
</thead>
<tbody id="serverTable">
</tbody>
</table>
JSON Example
{
"servers": [
{
"progress": 100,
"id": 11111111,
"imageId": 1,
"flavorId": 1,
"status": "ACTIVE",
"name": "SERVER-1",
"hostId": "abcdefghijklmnopqrstuvwxyz",
"addresses": {
"public": [
"1.1.1.1"
],
"private": [
"2.2.2.2"
]
},
"metadata": {}
},
{
"progress": 100,
"id": 22222222,
"imageId": 2,
"flavorId": 2,
"status": "ACTIVE",
"name": "Server-2",
"hostId": "zxywufvslakdkdkdkdkdkdkdkdk",
"addresses": {
"public": [
"3.3.3.3"
],
"private": [
"4.4.4.4"
]
},
"metadata": {}
}
]
}
jQuery version 1.5.1
jQuery-tmpl
version beta 1
I solved the issue by changing the success function and adding an explicit parse of the JSON to an array.
var servers = jQuery.parseJSON(result);
$('#serverTemplate').tmpl(servers).appendTo('#serverTable');