Datatable returns all the data when server side is set to true - datatables

I have the following code where I want to use server side to lazy load my data. My goal is to display 10 records per page. The rest of the data should be loaded as and when the user clicks on a particular page.
What's happening now is that the datatable displays all the records at once. Can someone help me fix this issue?
var table = $("#members").DataTable({
"processing": true,
"serverSide": true,
paging: true,
"pagingType": "full_numbers",
"iDisplayLength": "10",
"length": "10",
ajax: {
url: "/api/members",
dataSrc: "",
},
columns: [
{
data: "cardNumber"
},
{
data: "registrationDate",
},
{
data: "fullName",
},
{
data: "address"
},
{
data: "phoneNumber"
},
{
data: "email"
}
]
});
Here's the API code:
// GET /api/members
public IEnumerable<MemberDto> GetMembers(string query = null)
{
var membersQuery = _context.Members.ToList();
if (!String.IsNullOrWhiteSpace(query))
membersQuery = membersQuery.Where(c => c.FullName.Contains(query.ToUpper())).ToList();
var memberDtos = membersQuery.ToList()
.Select(Mapper.Map<Member, MemberDto>);
return memberDtos;
}

Related

Trying to do a sum on data tables, but its only suming first page

I'm trying to sum columns in a data table. But it is only suming the first page?
The two variables Requiredone and Bookedtwo only sum the values from the first page of the data, not the entire data set :s
var sTable = $('.datatable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bScrollCollapse": true,
"aaSorting": [[1, "desc"]],
"bServerSide": true,
"bProcessing": true,
"sAjaxSource": CycleTimeReport,
"aoColumns": [
{ "sName": "one", "sClass": "ellipsis" },
{ "sName": "two", "sClass": "ellipsis" }
],
"fnServerData": function (sSource, aoData, fnCallback) {
var data = new Object();
data.jsonAOData = JSON.stringify(aoData);
dataToSend = data;
$.ajax({
contentType: "application/json; charset=utf-8",
type: "POST",
url: sSource,
data: JSON.stringify(dataToSend),
success: function (msg) {
fnCallback(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (document.Invoice.hostname == "localhost") {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
}
});
},
"fnFooterCallback": function (nRow, aaData, iStart, iEnd, aiDisplay) {
var Requiredone = 0;
var Bookedtwo = 0;
for (var i = 0; i < aaData.length; i++) {
Requiredone+= aaData[i][2] * 1;
Bookedtwo += aaData[i][3] * 1;
}
},
"oLanguage": {
"sSearch": "_INPUT_"
},
"fnInitComplete": function (oSettings, json) {
},
"bSortCellsTop": true
});
You are using server-side processing of the data. So your datatable-object only has the data for the currently displayed page. You have to implement the sum on the server-side and add it to the JSON-response or do it in an extra ajax-request.
Another option would be to disable the server-side processing and pre-populate the table element or fill the aaData-property of the datatales-settings with a json object containing all data.

Datatables - passing one data of the selected row to a modal

I have a datatable that has an edit button on each row. When I click the edit button, a function opens a modal to display the data of the selected record.
Initially, I just want to get the id(which I referred to as PID) of the selected record. However according to my code, I am not sure how to extract the value passed. I kept on getting undefined response.
Please advise on any errors in my code or is there a better way to do this.
Thanks
select: true,
ajax: {
url: "people-grid-data.php",
type: "POST",
},
columnDefs: [{
"targets": [3, 4, 6, 7, 8, 9],
"visible": false,
"searchable": true
},
],
columns: [
{
"width":"2%",
"render": function (data, type, full, meta) {
return "<button type='button' class='btn btn-xs' data-toggle='modal' data-target='#editPersonModal'>Edit </button>";
},
},
{
"data": "PID",
render: getImg
},
{
"data": "PID"
},
{
"data": "personName"
},
{
"data": "PeopleRemarks"
}
],
"order": [
[2, 'asc']
]
});
$('#editPersonModal').on('show.bs.modal', function (data, type, full, meta) {
console.log("Data ID---"+data['PID']);
});
i have a button in my grid , you open your modal with this, using data atributes
render: function (data, type, row) {<a data-info="' + row.IdUser + '" data-toggle="modal" data-target="#modalGridTable" ...
in row.IdUser i have my id. now when i click in $('#modalGridTable').on('show.bs.modal', function (event)...
var button = $(event.relatedTarget);
var id = button.data('info');
var data = Grid.ajax.json().data;
function getDataJson(IdUsuario) {
return data.filter(
function (data) {
return data.IdUser === IdUser;
}
);
}
var result = getDataJson(id);
so you can read this example:
result[0].Phone

Sort icon not changing in Datatable server side processing

When I use server side processing in datatable the sorting works but the sort icon does not change and stays in same direction. Below is the code snippet of my datatable configuration.
$('#dtSearchResult').DataTable({
"filter": false,
"pagingType": "simple_numbers",
"orderClasses": false,
"order": [[0, "asc"]],
"info": true,
"scrollY": "450px",
"scrollCollapse": true,
"bLengthChange": false,
"searching": true,
"bStateSave": false,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": VMCreateExtraction.AppSecurity.websiteNode() + "/api/Collection/SearchCustIndividual",
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "ccUid", "value": ccUid });
//Below i am getting the echo that i will be sending to Server side
var echo = null;
for (var i = 0; i < aoData.length; i++) {
switch (aoData[i].name) {
case 'sEcho':
echo = aoData[i].value;
break;
default:
break;
}
}
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
success: function (msg, a, b) {
$.unblockUI();
var mappedCusNames = $.map(msg.Table, function (Item) {
return new searchGridListObj(Item);
});
var data = {
"draw": echo,
"recordsTotal": msg.Table2[0].TOTAL_NUMBER_OF_RECORDS,
"recordsFiltered": msg.Table1[0].FILTERED_RECORDS,
"data": mappedCusNames
};
fnCallback(data);
$("#dtSearchResult").show();
ko.cleanNode($('#dtSearchResult')[0]);
ko.applyBindings(VMCreateExtraction, $('#dtSearchResult')[0]);
}
})
},
"aoColumns": [{
"mDataProp": "C_UID"
}, {
"mDataProp": "C_LAST_NAME"
}, {
"mDataProp": "C_FIRST_NAME"
}, {
"mDataProp": "C_USER_ID"
}, {
"mDataProp": "C_EMAIL"
}, {
"mDataProp": "C_COMPANY"
}],
"aoColumnDefs": [{ "defaultContent": "", "targets": "_all" },
//I create a link in 1 st column
]
});
There is some configuration that I am missing here. I read on datatable forums and the only issue highlighted by people was that draw should be same as what we send on server side.
For anyone looking for an answer to this. Sad but i had to write my own function as below:
function sortIconHandler(thArray, sortCol, sortDir) {
for (i = 0; i < thArray.length; i++) {
if (thArray[i].classList.contains('sorting_asc')) {
thArray[i].classList.remove('sorting_asc');
thArray[i].classList.add("sorting");
}
else if (thArray[i].classList.contains('sorting_desc')) {
thArray[i].classList.remove('sorting_desc');
thArray[i].classList.add("sorting");
}
if (i == sortCol) {
if (sortDir == 'asc') {
thArray[i].classList.remove('sorting');
thArray[i].classList.add("sorting_asc");
}
else {
thArray[i].classList.remove('sorting');
thArray[i].classList.add("sorting_desc");
}
}
}
}
tharrray-> The array of all row headers(You can just write a jquery selector for this).
sortCol->Column on which sort is clicked (Datatable param iSortCol_0)
sortDir -> Sorting direction (Datatable param sSortDir_0)
I know this is an old thread, but make sure you don't have an .off() somewhere associated with the tables capture group in jQuery. I had a click event that (for some reason) I attached an off function to.. Took me 3 days to find it.

datatables with fixedheader: row click function giving error on fixed cols

I have an on click function storing the row data in the console log
if you click on the first two columns, you'll notice the function returns undefined, however any of the unfrozen columns returns the data object
I know that this has todo with the fact that the fixedcolumns are created in a cloned table, i was wondering if there was any workaround to this?
// Server-side processing with object sourced data
var $table;
$(document).ready(function() {
$table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/ssp/objects.php",
dom: "<'row'<'col-md-6 'l><'col-md-6 pull-right'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"columns": [
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{ "data": "salary" }
],
scrollY: "600px",
scrollX: "100%",
scrollCollapse: true,
"pageLength": 5,
lengthMenu: [[5, 10, 25, 50 ], [5, 10, 25, 50]],
order: [[ 1, "asc" ]],
} );
new $.fn.dataTable.FixedColumns( $table, {
leftColumns: 2
} );
$table.on("click", "tr",function(){
var aData = $table.row( this ).data();
console.log( aData);
} );
} );
here is my example code in action
You can use fnGetPosition to get information about row index.
From the manual:
This function is functionally identical to fnGetPosition in
DataTables, taking the same parameter (TH, TD or TR node) and
returning exactly the the same information (data index information).
The difference between the two is that this method takes into account
the fixed columns in the table, so you can pass in nodes from the
master table, or the cloned tables and get the index position for the
data in the main table.
Your code needs to be modified as follows:
var fc = new $.fn.dataTable.FixedColumns( $table, {
leftColumns: 2
});
$table.on("click", "tr", function(){
var aData = $table.row(fc.fnGetPosition(this)).data();
console.log(aData);
});
See this example code for demonstration.

How to control the Kendo Grid?

How do I control how many rows appear in a kendo grid? Real Estate is limited, so I need to have a lot of info in a pretty compact space. I'm trying to pack everything in my grid in a 300-pixel high area.
The issue I'm having is that all 200-plus rows of data that are being returned from my MVC JsonResult in my controller are displaying at once, on a single page. Not quite exactly what I'm looking for.
Code is below, if someone a little more knowledgeable about formatting a kendo grid could help out, I'd appreciate it.
Thanks!
-RC
{}
var RemoteJsonData_Call = new kendo.data.DataSource({
transport:
{
read: {
type: "GET",
dataType: "json",
url: resourceURL_Call
},
pageSizes: 8,
serverPaging: true
},
schema: {
model: {
ScheduleData: {
extensionDataField: {
fields: {
ScheduleDate: { type: "date" },
ScheduleAmount: { type: "number" },
SchedulePrice: { type: "number" },
ScheduleNotes: { type: "string" }
}
}
}
}
}
})
$('#callSched').kendoGrid({
height: '300',
sortable: true,
reorderable: true,
resizable: true,
pageable: {
numeric: true,
refresh: true,
pageSizes: true,
previousNext: true,
input: true,
info: true
},
columns: [
{
field: "ScheduleDate",
title: "Date",
template: "#= kendo.toString(kendo.parseDate(ScheduleDate, 'MM-dd-yyyy'), 'MM-dd-yyyy') #"
},
{
field: "ScheduleAmount",
title: "Amount",
},
{
field: "SchedulePrice",
title: "Price"
},
{
field: "ScheduleNotes",
title: "Notes"
}
], dataSource: RemoteJsonData_Call
});
{}
The problem is that you have defined that the paging is done in the server when it is not. You should say:
serverPaging: false
or just nothing since the default value is false.
With this you should have a grid with the number of pixels specified in the height option (in your example 300 pixels). Other options in you example are correct.
You have server paging and page size set up incorrectly here:
var RemoteJsonData_Call = new kendo.data.DataSource({
transport:
{
read: {
type: "GET",
dataType: "json",
url: resourceURL_Call
},
pageSizes: 8,
serverPaging: true
},
It should be:
var RemoteJsonData_Call = new kendo.data.DataSource({
transport:
{
read: {
type: "GET",
dataType: "json",
url: resourceURL_Call
}
},
pageSize: 8,
serverPaging: true
The config options were in the wrong place, and "pageSizes" was misspelled, it should be "pageSize" with no "s" on the end.
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-pageSize