datatables server side processing(load on demand) - javascript

i am trying to do a server side processing which is load on demand , i am using mvc to develop my application
the following is my code on the datatables js class,
var initTrackingTable = function () {
var table = $('#tableCategoryList');
var daterange = $("#daterangepicker").val();
val_CategoryName = $("#SearchTextBox").val();
//val_Daterange = $("#trackingForm").find("[name='daterangepicker']").val();
settingsInitEmpty = {
ajax: ({
url: "/Product/LoadCategoryData?category=" + val_CategoryName,
type: "POST",
datatype: "json"
}),
// ### FOR SERVERSIDE LODING
processing: true,
serverSide: true,
filter: false,
orderMulti: false,
columns: [
{ data: "category_id", name: "category_id", autoWidth: true },
{ data: "category_name", name: "category_name", autoWidth: true, render: function (data, type, row) { return '<span class="">' + data + '</span>' } },
{ data: "sort_order", name: "sort_order", autoWidth: true },
],
initComplete: function (settings, json) {
$("#tableCategoryList").parent().addClass("tableTransactionGridWrapper")
}
};
categoryTable = table.DataTable(settingsInitEmpty);
}
on the category_name there, i wish to put the hyperlink, however the hyperlink i intend to put the category_id as a query string parameter so i am able to edit the category. may i ask is this achievable? if yes, how the code suppose to be?

Related

Data is not populated in the grid after the ajax call

I am trying to use js grid for my application. I am trying to populate the grid after ajax request but it do not seem to work as expected.
I am trying with SQL Server as back end and web application is asp.net MVC
This is my code in the html
var table;
var result;
var $j = jQuery.noConflict();
$j(document).ready(function () {
table = $j('#grid').jsGrid({
height: "60%",
width: "50%",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
controller: {
loadData: function (filter) {
var d = $j.Deferred();
$j.ajax({
type: "POST",
contentType: "application/json",
url: "#Url.Action("LoadData", "User")",
datatype: "json",
data: filter
#*success: function (data) {
result = data.data;
console.log("result", result);
d.resolve(result)
},
error: function (data) {
window.location.href = '#Url.Action("Error", "Audit")';
}*#
}).done(function (data) {
console.log("response", data);
console.log("data.data", data.data);
d.resolve(data)
});
return d.promise();
},
fields: [
{ name: "LastName", type: "text"},
{ name: "FirstName", type: "text"},
{ name: "Email", type: "email"},
{ name: "PhoneNumber", type: "number"},
{ type: "control" }
]
}
});
});
In Controller I return
''return Json(new { data }, JsonRequestBehavior.AllowGet);''
I expect the json data to bind in the div. But it did not ? Thanks
Ok, so I've had this problem recently.
First off, change your "height" to px, auto, or get rid of it entirely. It's not doing what you think it's doing.
Next, since you have paging, you need to return your data in the following format:
{
data: [{your list here}],
itemsCount: {int}
}
It's barely in the documentation, as it's inline and not very obvious. (Bolding mine.)
loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when pageLoading is true instead of object the structure { data: [items], itemsCount: [total items count] } should be returned). Accepts filter parameter including current filter options and paging parameters when
http://js-grid.com/docs/#controller

Kendo Grid multiselect checkboxes

I have a Treeview. On selecting the edit of the treenode a kendo grid for Roles will be displayed and few textboxes (where is edit other properties for roles). The kendo grid for roles have checkboxes and Rolenames. My current code is working if I select one checkbox.
What I need is how I get the array of the ids of the roles if I check multiple checkboxes. Tried multiple ways but I am not getting the list of ids when multiple checkboxes are selected. On click edit of the node EditNode is triggered and on click of save the 'click' is trigerred.
Below is my code:
function editNode(itemid) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node }))
.appendTo("body")
.kendoWindow({
title: "Node Details",
modal: true,
open: function () {
console.log('window opened..');
editDS = new kendo.data.DataSource({
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: {// define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { editable: false, nullable: false, type: "string" },
name: { editable: true, nullable: true, type: "string" },
NodeId: { editable: false, nullable: false, type: "string" },
}
},
},
transport: {
read: {
url: "/Services/MenuServices.asmx/getroles",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
datatype: "json",
},
}
});
rolesGrid = $("#kgrid").kendoGrid({
dataSource: editDS,
height: 150,
pageable: false,
sortable: true,
binding: true,
columns: [
{
field: "name",
title: "Rolename",
headerTemplate: '<span class="tbl-hdr">Rolename</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
template: kendo.template("<input type='checkbox' class = 'checkbox' id='chkbx' data-id='#:Id #' />"),
attributes: {
style: "vertical-align: top; text-align: center;"
}
},
],
}).data('KendoGrid');
},
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var LinKLabel = $('#LL').val();
var roles = $(chkbx).data('roleid');
console.log(PageLocation);
node.text = undefined;
node.set("LINK_LABEL", LinKLabel);
node.set("Roles", roles);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("LINK_LABEL", LinKLabel);
treenode.set("id", Id);
treenode.set("roles", roles);
treenode.LINK_LABEL = LinKLabel;
treenode.ID = Id;
treenode.roles = roles;
var rid = $(chkbx).data('roleid');
$.ajax({
url: "/Services/MenuServices.asmx/UpdateTreeDetails",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: JSON.stringify({ "Json": treenode })
});
console.log(JSON.stringify(treenode));
})
}
I'm assuming you want to get those ids in this line:
var roles = $(chkbx).data('roleid');
Right? What I don't know is the format you want to get that data. With the following code you can get the roles data in an array objects like this { id: 1, value: true }, check it out:
var grid = $("#grid").data("kendoGrid"),
ids = [];
$(grid.tbody).find('input.checkbox').each(function() {
ids.push({
id: $(this).data("id"),
value: $(this).is(":checked")
});
});
Demo. Anyway you want it, you can change it inside the each loop.
Update:
To get only the checked checkboxes, change the selector to this:
$(grid.tbody).find('input.checkbox:checked')
Demo

Getting Uncaught TypeError: Cannot read property 'uid' of undefined(anonymous function) when trying to bind data to Kendo Grid

I have a Kendo grid that is being generated in an external javascript file as well as having data bound to it, and I been getting
Uncaught TypeError: Cannot read property 'uid' of undefined(anonymous function)
I have no idea where this 'uid' is coming from, I have been stepping through the code and and I think the error is coming in when trying to pass the returned data to the datasource of the grid.
My grid is this (and the grid does appear in the view)
function ShowAdministratorsGrid() {
$("#adminGrid").kendoGrid({
dataSource:[{
data: GetAdministratorsInformation()
}],
columns: [{
field: "AdministratorName",
title: "AdministratorName"
},
{
field: "DateCreated",
title: "DateCreated"
},
{
field: "CreatedBy",
title: "CreatedBy"
}],
Scrollable: true,
Sortable: true,
Pageable: [{
Refresh: true,
PageSizes: true,
ButtonCount: 5
}],
Selectable: true,
Events: function (e) {
e.onRowSelect();
}
})
}
The datasource data is this
function GetAdministratorsInformation() {
$.ajax({
type: "GET",
url: AddURLParam.AddGetAdminInformationURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
GetAdministratorData(data);
}
})
}
The GetAdministratorData function is this..
function GetAdministratorData(admindata) {
administratorName = admindata.administratorName,
dateCreated = admindata.dateCreated,
createdBy = admindata.createdBy
}
I am getting the returned data, as you can see in ScreenShot1
If you take a look at ScreenShot2, I am getting an undefined when adding the returned values to the GetAdministratorData, here is the screenshot
So I am thinking that is why I am getting the error on populating the KendoGrid, does anyone see what I am doing wrong or where things are going wrong?
EDIT
I narrowed down where the error is being thrown..
data is an array. so you need to access the item by admindata[0].administratorName.
Or loop through the array, I don't really know what you're trying to do. In any case, data is an array, which (right now) just contains the one object.
Also, on this line
dataSource:[{
data: GetAdministratorsInformation()
}],
GetAdministratorsInformation doesn't really return anything since it's an async operation. If you want to set the data, you'll need to do it on your success callback in GetAdministratorsInformation
And in your columns settings, the field names are pascal case AdministratorName while in the data object they're camel case administratorName
To recap:
function CreateAdministratorsKendoGrid(administratorData) {
$("#adminGrid").kendoGrid({
dataSource:[{
data: administratorData
}],
columns: [{
field: "administratorName",
title: "Administrator name"
},
{
field: "dateCreated",
title: "Date created"
},
{
field: "createdBy",
title: "Created by"
}],
Scrollable: true,
Sortable: true,
Pageable: [{
Refresh: true,
PageSizes: true,
ButtonCount: 5
}],
Selectable: true,
Events: function (e) {
e.onRowSelect();
}
})
}
function InitializeAdministratorsGrid() {
$.ajax({
type: "GET",
url: AddURLParam.AddGetAdminInformationURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
CreateAdministratorsKendoGrid(data);
}
})
}
InitializeAdministratorsGrid();
Resolved issue as follow:
var objectDDL = e.container.find("select:eq(0)").data("kendoDropDownList");
var rows = jQuery.makeArray(objectDDL.dataSource.data());
$.each(rows, function (index, value) {
objectDDL.dataSource.remove(rows[index]);
});

Data table with bootstrap using angularjs app

I am using jquery data table with bootstrap and facing one little issue which i don't understand.
Here is my code
$scope.LoadTypesView = function() {
$http({
method : 'POST',
url : "servierapi.php",
data : SessionId, // pass in data as strings
headers : { 'Content-Type': 'application/json' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if(data.aaData.status=="success") // i get two message error and success and work well
{
$scope.Type = data.aaData.response;
var oTable = $('#typess').dataTable( {
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": [ "csv", "xls", "pdf" ]
}
]
},
"bProcessing": true,
"sAjaxSource": '$scope.Type'
} );
$('#types').modal('show');
}
});
};
Here is my json array which i receive from server and assign to $scope.Type variable
{"aaData":{"status":"success","response":[{"UserTypeId":"1","TypeName":"Admin","CreatedOn":"2014-02-24 00:00:00","AssignedUsers":[{"UserId":"7","UserTypeId":"1","UserRegionId":"1","UserDepartmentId":"1","UserDesignationId":"1","CNIC":"xxxxxxxx","FirstName":"Hafiz","LastName":"Haseeb","Dob":"January 1,1970","PhotoName":"","PhotoPath":"","Email":"xxxxxx","EducationLevel":"","MartialStatus":"","City":"","State":"","Country":"","MobileNumber":"","EmergencyNumber":"","AddressOne":"","AddressTwo":"","CreatedOn":"0000-00-00 00:00:00","Salary":""}]}]}}
I also check JSON array on this link http://jsonformatter.curiousconcept.com/ and json array is valid.
why i am getting this error
Data Tables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.?
You are using "sAjaxSource": '$scope.TypeId' as a string , this is variable you can use this like sample code and some data functions and its parameters
"sAjaxSource": $scope.TypeId,
"sAjaxDataProp": "aaData",
'fnServerParams' : function (aoData) {
aoData.push({"name":"SessionId", "value":Session_Id});
}
I hope this will help to solve your problem
this.Display_error = false; this.sign_report.value.status = 0;
this.signOptions = {pagingType: 'full_numbers', paging: true, ordering: false, dom: 'Bflrtip', pageLength: 10,
processing: true, serverSide: true, buttons: ['copyHtml5', {extend: 'excelHtml5', text: 'To Excel', title: this.in_header},
{extend: 'pdfHtml5', text: 'To Pdf', title: this.in_header},
{extend: 'print', text: 'Direct Print', title: this.in_header}],
ajax: (dataTablesParameters: any, callback) => {
this.http.post<DataTablesResponse>(this.db.CheckIf_url, dataTablesParameters, {}).subscribe(resp => {
console.log(resp.data); this.signinoutmodel = resp.data;
callback({
draw: resp.draw,
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: resp.data
});
});
},
fnServerParams: function(dt) {
dt.signedfrom = fd.signedfrom;
dt.signedtill = fd.signedtill;
dt.status = fd.status;
dt.sort_event = fd.sort_event;
dt.signed_in_at = fd.signed_in_at;
dt.signed_out_at = fd.signed_out_at;
dt.sort_category = fd.sort_category;
},
columns: [{ data: 'tblid' }, { data: 'staff_id' }, { data: 'fullname' }, { data: 'event_name' },
{ data: 'sign_in' }, { data: 'sing_out'}, { data: 'date_signed' } ]
};

Kendo UI Grid - Update not persisting

Been trying to do an update on a Kendo grid and I'm having issues.
I'm using Rails as the back-end and when I do the update, the server seems to be showing that everything worked:
Started PUT "/" for 127.0.0.1 at 2012-02-12 17:28:19 -0600
Processing by HomeController#index as
Parameters: {"models"=>"[{\"created_at\":\"2012-02-08T17:34:50Z\",
\"first_name\":\"Milla\",\"id\":2,\"last_name\":\"sfasfsdf\",\"password\":\"\",
\"updated_at\":\"2012-02-08T17:34:50Z\",\"user_name\"
:\"\"}]"}
Rendered home/index.html.erb within layouts/application (3.0ms)
Completed 200 OK in 89ms (Views: 88.0ms | ActiveRecord: 0.0ms)
However, when I refresh the view, nothing has changed. When I checked the database, of course no changes had taken place there either.
I went through the documentation here about how to do edits in the grid: http://demos.kendoui.com/web/grid/editing.html
And I watched Burke Hollands video about how to set up the grid to work with Rails: http://www.youtube.com/watch?v=FhHMOjN0Bjc&context=C3f358ceADOEgsToPDskKlwC22A9IkOjYnQhYyY9HI
There must be something that I haven't done right, but I'm just not seeing it.
Here's my code that works with the Kendo stuff:
var User = kendo.data.Model.define({
id: "id",
fields: {
first_name: { validation: { required: true } },
last_name: { validation: { required: true } }
}
});
var UsersData = new kendo.data.DataSource({
transport: {
read: {
url: "/users.json"
},
create: {
url: "/users/create.json",
type: "POST"
},
update: {
type: "PUT"
},
destroy: {
type: "DELETE"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 5,
schema: {
model: User
}
});
$("#users-grid").kendoGrid({
dataSource: UsersData,
navigatable: true,
editable: true,
selectable: true,
pageable: true,
sortable: true,
toolbar: ["create", "save", "cancel"],
columns: [
{
field: "first_name",
title: "First Name"
},
{
field: "last_name",
title: "Last Name"
},
]
});
Some more research and I've got it working like this...
I added a route to override the 7 RESTful routes that Rails gives you by default. In your Routes.rb files, add this line...
match 'users' => 'users#update', :via => :put
Which basically says we are going to handle all puts by going to the update definition on the controller.
Now in the controller definition, you want to handle the update a bit differently since it's not RESTful. You need to first parse the JSON that you are sending via the parameterMap and then iterate through the objects updating with the object attributes...
def update
respond_to do |format|
#users = JSON.parse(params[:models])
#users.each do |u|
user = User.find(u["id"])
unless user.nil?
user.update_attributes u
end
end
format.json { head :no_content }
end
end
You can also modify your datasource because the url key can take a function:
var UsersData = new kendo.data.DataSource({
transport: {
read: {
url: '/users.json',
dataType: 'json'
},
update: {
url: function (o) {
return '/users/' + o.id + '.json'
},
dataType: 'json',
type: 'PUT'
},
destroy: {
url: function (o) {
return '/users/' + o.id + '.json'
},
dataType: 'json',
type: 'DELETE',
},
create: {
url: '/users.json',
dataType: 'json',
type: 'POST'
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 5,
schema: {
model: User
}
});

Categories