Pagination on Kendo UI Grid is not working - javascript

I'm displaying a grid with remote data, if I don't add pagination the full set of data is displayed, of course this is not desired.
The following is the code I'm using to display data on a grid:
var ds = new kendo.data.DataSource({
transport: {
read: {
url: "http://127.0.0.1:81/SismosService.svc/usuario/index",
dataType: "json"
}
},
schema: {
data: "Response"
},
pageSize: 5
});
$("#usuariosGrid").kendoGrid({
pageable: {
refresh: true
},
columns: [
{ field: "UsuarioId", title: "ID", width: "100px" },
{ field: "Nombre", title: "Nombre", width: "100px" },
{ field: "ApellidoP", title: "Apellido Paterno", width: "100px" },
{ field: "ApellidoM", title: "Apellido Materno", width: "100px" },
{ command: [{ text: "Editar", click: editFunction }, { text: "Eliminar", click: deleteFunction }], title: " ", width: "200px" }
],
dataSource: ds
});
This renders a grid with 5 items on it, but that's it, I can't navigate through the rest of the entries. The number of pages and items to display is marked as zero, disabling the navigation controls.
Am I missing something in my cofiguration? Thanks for any help you can provide.

When paging is done in the server (check serverpaging), you need to return the total number of records. See total for information.

I had the same issue because I misunderstood serverPaging. If you set serverPaging to true, you also have to modify what the server returns.
Previously, I had the server returning all of the data. To fix this, I used ToDataSourceResult to modify what my server returns.
See:
How to implement Server side paging in Client side Kendo UI grid in asp.net mvc

spend a day on this minor issue, all you have to do is return the total number of records, if your service doesn't return the total number of records, do the following
schema: {
data: "Response"
},
total: function(response)
{
return response."your method name".length;
}

Related

Kendo UI grid export excel and pdf export, no file created

I am trying to create a kendo grid with excel export. My data is shown precisely as I want it and the grid works fine. However, the saveAsExcel function triggers the excelExport event, but no file is created. Same problem with the pdf export.
Here is my grid options:
grid = $("#grid").kendoGrid({
toolbar:["excel","pdf"],
height: 500,
scrollable: true,
groupable: true,
sortable: true,
filterable: false,
excel: {
allPages:true,
filterable:true
},
excelExport: function(e) {
console.log('Firing Export');
console.log(e.workbook);
console.log(e.data);
},
pdfExport: function(e){
console.log('PDF export');
},
columns: [
{ field: "date", title: "Time", template: "#= kendo.toString(kendo.parseDate(date), 'MM/dd/yyyy') #", width: '120px'},
{ field: "customer", title: "Customer" },
{ field: "amount", title: "Total", format: "{0:c}", width: '70px', aggregates: ["sum"]},
{ field: "paid_with", title: "Payment", width: '130px'},
{ field: "source", title: "Source" },
{ field: "sale_location", title: "Sale Location" }
]
}).data("kendoGrid");
This ajax is called whenever the search parameters for the data is changed. Where I refresh the datasource.
$.ajax({
'url':'/POS/ajax/loadTransactionsDetailsForDay.php',
'data':{
filters
},
'type':'GET',
'dataType':'json',
'success':function(response) {
var dataSource = new kendo.data.DataSource({
data: response.data.invoices,
pageSize: 100000,
schema: {
model: {
fields: {
date: {type: "string"},
customer: { type: "string" },
amount: { type: "number" },
paid_with: {type: "string"},
source: {type:"string"},
sale_location: {type:"string" }
}
}
}
});
grid.setDataSource(dataSource);
grid.refresh();
}
});
The output from my console log is.
Firing Export.
A worksheet object.
Object {sheets: Array[1]}sheets: Array[1]0: Objectlength: 1__proto__: Array[0]__proto__: Object
and and array with these objects for every row in the grid:
0: o
_events: Object
_handlers: Object
amount: 40.45
customer: "customer 1"
date: "2015-11-25T00:00:00-08:00"
dirty: false
employee: 23
paid_with: "Check"
parent: ()
sale_location: "Main"
source: "POS"
uid: "70b2ba9c-15f7-4ac3-bea5-f1f2e3c800d3"
I have the latest version of kendo, I am loading jszip. I am running it on the latest version of chrome.
I have tried all kinds of variations of this code I can think of, including removing my schema, initializing the kendo anew every time in the callback.
Anyone got any idea why this would not work?
Every example on this I can find make it look super simple, just create the grid and call export... So I have to have overlooked something.
I am grateful for any ideas about this.
Thanks.
It could be because the filename is missing.
Here the part with the filename added:
excel: {
allPages:true,
filterable:true,
fileName: "Kendo UI Grid Export.xlsx"
},
You can take a look here : Grid Excel Export
And here for the pdf: Grid Pdf Export
I have some following suggestion.
Can you add kendo deflate pako script file into your code and try.
Then remove the pdf export event and just try to export a pdf with toolbar default functionality..check whether its working or not.
try to add a data-source ajax call with in a grid option using kendo-transport technique with read method. http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport

Kendo UI grid filter doesn't work when opening a popup before

I have a Kendo UI grid where some of the columns can be filtered. For each row in that column, you can open a popup to see some details to the specific entry.
I can open the popup without any problems. But: after closing it and trying to filter any of the columns, I get the following error: JavaScript runtime error: Unable to get property 'toggle' of undefined or null reference
If I filter a column before I open a popup, it works like a charm.
If I filter a column and then open the popup, the already filtered column can be filtered again but the others not.
I don't know why I can't filter columns after opening and closing the popup.
Any ideas or hints would be really helpful. Thanks
HTML:
<div id="windoofTestOuter"><div id="windoofTest"></div></div>
<div id="processGrid"></div>
My grid:
$("#processGrid").kendoGrid({
sortable: true,
pageable: true,
selectable: true,
filterable: {
extra: false
},
dataSource: {
type: "aspnetmvc-ajax",
transport: {
read: {
url: "/Home/GetProcesses",
cache: false,
type: "POST",
dataType: "json"
},
parameterMap: function (data) {
return $.extend({}, data, { sort: data.sort, filter: data.filter });
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
page: "#ViewBag.ProcessPage",
schema: { data: "Data", total: "Total", model: { id: "Id" } },
pageSize: "#(#Model.MaxCountToShow)"
},
columns: [
{ field: "ErrorDateTime", title: "ProcessDateTime", width: "170px"/*, filterable: { ui: dateFilter }*/ },
{ field: "Name", title: "Processtype", attributes: { value: "type" }, width: "240px;", filterable: { ui: processtypeFilter} },
{ field: "Service", title: "Service", width: "181px;", filterable: { ui: serviceFilter } },
{ field: "Operation", title: "Operation", width: "130px", filterable: { ui: operationFilter } }
]
}).data("kendoGrid");
The link/string which shall open the popup:
function createProcessActionString(process) {
var det = '<a class="makeANiceMouse" onclick="processDetailUrl(' + process.Id + ', ' + grid.dataSource.page() + ')">Details</a>';
return det;
}
My popup:
function processDetailUrl(id, page) {
var windoof = $("#windoofTest").kendoWindow({
width: "1150px",
height: "300px",
content: det,
title: "Process Details",
actions: ["Minimize", "Maximize", "Close"],
close: function (e) {
windoof.data("kendoWindow").content(" ");
}
});
windoof.data("kendoWindow").center().open();
}
I deleted the unnecessary columns and so on..
EDIT: I tried to intitialize the filter in the filterMenuInit. After opening and closing the popup, I clicked on the filter icon of one of the columns, and I get the error : JavaScript runtime error: Unable to get property 'toggle' of undefined or null reference . The same one as before.
EDIT: I used the windoof.destroy() but the filters weren't accessable afterwards.
EDIT solution: I have a workaround for working with the filters again. I just fake a click on each of it before I open a popup. It's not beautiful but it serves me so far.
BUT It seems like everything gets kicked/killed by that damn popup. I can't even access the grid's datasource anymore.. It's strange...
I'm dealing with the same issues but got well passed the Data not being there. Check out or use onDataBound and use e.sender to get a handle to the Grid Object opposed to .data("KendoGrid") from the onClose of the popup this is what fixed it for me. I'm still trying to get my filters to work though after the pop up closes.

data not displaying in JQgrid when using datatype:function?

Edit:
Okay I think it's because when I assign sumColumnModel to colModel sumColumnModel is empty because sumColumnModel is only non-empty within the success function. So is there any way I can get that variable out of the success function and use it in colModel?
I am using a function to get my data and I am getting the data out just fine. I get this JSON from data.d:
"{"Page":1,
"TotalPages":5.0,
"TotalRecords":122,
"ColumnModel": [
{"name":"Description","sorttype":"string","align":"center"},
{"name":"Matrix","sorttype":"string","align":"center"},
{"name":"AvailableReports","sorttype":"string","align":"center","hidden":true},
{"name":"Classification","sorttype":"string","align":"center","hidden":true}
],
"Submissions":[
{"DateSubmitted":"4/23/2014","DateSampled":null,"Matrix":"Sometype","Status":"Completed","SubmissionId":"001","Description":"description","Company":null,"Classification":null,"AvailableReports":7},
{"DateSubmitted":"4/23/2014","DateSampled":null,"Matrix":"sometype","Status":"Completed","SubmissionId":"002","Description":"description","Company":null,"Classification":null,"AvailableReports":6}
]}"
I am currently using this jsonreader:
jsonReader: {
repeatitems: false,
root: function(obj) { return obj.Submissions; },
page: function(obj) { return obj.Page; },
total: function(obj) { return obj.TotalPages; },
records:function(obj) { return obj.TotalRecords; },
}
I tired putting in just 'Submissions' for the value of root in jsonreader but that didnt do the trick.
My column model is being edited in the success part of my ajax function call to correctly display certain columns that is done like this.
myData.ColumnModel.splice(0, 0,
{ name: "DateSubmitted", label: "Date Submitted", sorttype: "date", align: "center"});
myData.ColumnModel.push(
{ name: "Status", sorttype: "string", align: "center" },
{ name: "SubmissionId", label:"Submission Id", sorttype: "string", align: "center" });
sumColumnModel = myData.ColumnModel;
then I pass sumColumn as the Column model for the grid.
colModel: sumColumnModel,
Any idea why the grid isn't being populated?
So I wound up just initializing the colModel and then adding/subtracting things from it based on a couple drop down menus. It would be nice to know if I could actually get the col model out of the datatype:function but at this point I've just worked around it.

Lazy Load with Scrollable {Virtual:true} not working in Kendo UI Grid

I am facing an issue to implement lazy loading in kendo ui grid.
I added scrollable virtual property and backend server side code to handle it but issues is after adding scrollable property I am unable to see scroll bar in my Grid.
Even the selected rows (20 page size) disappears off the bottom of the grid into the hidden overflow area.
Here is my code.
var managecustomerGrid = $("#customerGrid").kendoGrid({
dataSource: {
schema: {
data: "results",
total : "totalRecords",
model: {
id: "SRNUMBER",
fields: {
SRNUMBER : {type: 'number'},
CUSTOMERNAME : {type: 'string'},
DATEPAID : {type: 'string'}
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 20,
batch: false,
transport: {
read: {
type: "POST",
url: "/customer/customer.cfc",
dataType: "json",
error: function (xhr, error) {
alert('Error In Getting Customer Information.');
}
},
parameterMap: function(options, type) {
return {
ntPageNumber: options.page,
ntRowLimit: options.pageSize,
vcSortOrder: JSON.stringify(options.sort),
vcFilterCondition: JSON.stringify(options.filter)
}
}
}
},
toolbar: kendo.template($("#template").html()),
height: 600,
scrollable: {
virtual: true
},
filterable: {
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
endswith: "Ends with",
eq: "Is equal to",
doesnotcontain: "Doesn't contain"
}
}
},
sortable: true,
columns: [
{ field: "SRNUMBER", title: "SR No.", width: "80px", template: "<span id='#=SRNUMBER#'>#=SRNUMBER#</span>"},
{ field: "CUSTOMERNAME", title: "Customer Name", width: "110px"},
{ field: "DATEPAID", title: "Date", width: "110px"},
{ command: ["edit","detail","cancel"], title: " ", title: "Actions", width: "130px", filterable: false, sortable: false}
]
});
Please let me know if any one find any issues. I am unable to get it.
The kendo grid does not really support Lazy Loading out of the box. It may be easier to instead just make a blank scroll-able grid (without paging), and then to populate the data with ajax calls. You can use $.merge() to append data to the data array with little to no impact on performance.
$.ajax({
url: '/getNextData',
data: { filter: 'foo', lastLoaded: $("#Grid").data("kendoGrid").dataSource.at($("#Grid").data("kendoGrid").dataSource.total()-1).ID },
dataType: "json",
success: function (newData) {
$("#Grid").data("kendoGrid").dataSource.data($.merge($("#Grid").data("kendoGrid").dataSource.data(), newData))
},
error: function (e) { console.log(e); }
});
In this ajax example I load the next data based on the current last item in the grid and a filter. I just append the response to the currently loaded data.
I faced the same issue, my problem was the controller code. Here I am posting my controller hoping it would help someone someday
public JsonResult GetJson(int? projectid,int skip, int take, int pageSize, int page)
{
using (sqlCon)
{
var myData = sqlCon.Query<Device>("Select * from workbook.dbo.TargetList", new { projectid = projectid });
var data = myData .Skip(skip).Take(pageSize).ToList();
var total = myData .Count();
var json = new { data = myData };
var jsonResult = Json(new {data= data, total= total}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
}

How to load JSON Data in jQuery-jTable plugin?

I am working on creating a table form using jTable plugin. It mainly focus for ASP or PHP MVC but I'm trying to implement it with javascript/html and mongo backend.
I went through entire jTable API documentation and I found out there is possibility of populating json schema api into table, quite similiar in flexigrid.
The code looks like:
$(document).ready(function () {
$('#feeds-table').jtable({
title: 'Accounts',
pageSize: 15,
ajaxSettings: {
type: 'GET',
dataType: 'json'
},
actions: {
},
fields: {
id: {
key: true,
list: false
},
username: {
title: 'Username',
width: '10%'
},
email: {
title: 'Email',
width: '10%'
},
applications: {
title: 'Applications',
width: '10%'
},
sites: {
title: 'Sites',
width: '10%'
},
verticals: {
title: 'Verticals',
width: '10%'
},
roles: {
title: 'Roles',
width: '10%'
},
profiles: {
title: 'Record date',
width: '30%',
type: 'date',
create: false,
edit: false
}
}
});
});
If anyone can help me to find out where should I use URL property or is there any other method in the API reference to GET the data and display in table. Please let me know!
You can directly load JSON data by setting the 'listAction' to a JSON document .
Example:
actions: {
listAction: 'url/file.json',
},
Your JSON file needs to have the same fields specified and the next structure:
{
"Result":"OK",
"Records":[
{"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":2,"Name":"Douglas Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":3,"Name":"Isaac Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":4,"Name":"Thomas More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
]
}
The common way is to point the 'listAction' to a server side script (PHP,ASP.NET...) that return the above JSON object.
Check the listAction API reference for more information:
ApiReference-listAction
Use the addRecord action. It gives you the option to specify clientOnly: true which will prevent jtable from making a server call when you edit a row.
More Information - jtable.org-addRecord

Categories

Resources