Why Kendo datasource functions is not called? - javascript

I am trying to bind returned data from datasource to grid but the problem is that non of my data source functions is called...
transactionHistoryGridDS: new kendo.data.DataSource({
error: function () {
alert("erroe")
},
complete: function () {
alert("completed")
},
success: function () {
alert("success");
},
transport: {
read: {
dataType: "json",
type: 'POST',
url: args.TransactionHistoryUrl,
data: {
id: function () {return vm.transactionHistoryParams.id },
originBranch: function () {return vm.transactionHistoryParams.originBranch },
take: function () {return vm.transactionHistoryParams.take },
skip: function () {return vm.transactionHistoryParams.skip }
}
},
schema: {
parse: function (data) {
alert("hey...")
return data;
},
data: "data",
total: "total",
},
pageSize: 20,
serverPaging: false
}
}),
When i call read datasource through below code
vm.transactionHistoryGridDS.read();
Ajax request is called and data successfully returned from the server,but non of the functions including success and error and complete and parse is called
and consequently, data is not bind to the grid.

I can see some bugs that need to be fixed before your grid will work.
First of all, schema, pageSize, serverPaging is on wrong indent level, it should be on same level as transport not inside it.
transport: {...},
schema: {...},
serverPaging: ...,
pageSize: ...
Every grid should have dataSource property, read will be called automatically and data will be populated, you dont need to set data to grid or call read() function:
$('#grid').kendoGrid({
dataSource: {
transport: {
read: {...}
}
}
});
In your case I assume vm is a grid so you need to set dataSource:transactionHistoryGridDS, check example links below
If you need to send data with request use parameterMap:
$('#grid').kendoGrid({
resizable: true,
filterable: true,
sortable: true,
pageable: {
pageSize: 10,
refresh: true,
pageSizes: [5, 10, 20, 100, 500, 1000]
},
dataSource: {
pageSize: 10,
serverPaging: true,
serverFiltering: true,
transport: {
read: {
url: 'url',
type: 'POST',
dataType: 'JSON',
contentType: 'application/json'
},
update: {...},
destroy: {...},
parameterMap(data, type) {
switch (type) {
case 'read':
let request = {};
request.page = data.page - 1;
request.page_size = data.pageSize;
request.sort = data.sort;
request.filter = data.filter;
return JSON.stringify(request);
case 'destroy':
return kendo.stringify(data);
default:
break;
}
}
}
}
});
There is two way of geting data from kendo dataSource request, first one it with complete function that is called when request and response is finished. The second is promise on every dataSource request.
First example: complete call
Second example: promise call

Related

How to check if the ajax call for jQuery DataTable has returned data

I am trying to load the jQuery DataTable from an AJAX call as in the code below. However I need to know if there is a callback for the DataTable to check if the AJAX call returned successfully or failed before the table is loaded.
$(function() {
$('#data-table').DataTable({
destroy: true,
responsive: true,
serverSide: false,
autoWidth: false,
paging: true,
filter: true,
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [5, 10, 25, 50, 75, 100],
ajax: {
url: 'https://jsonplaceholder.typicode.com/todos',
type: 'GET',
dataSrc: ''
},
columns: [{
title: 'Zone',
data: 'LastKnownZone',
}, {
title: 'HiƩrarchie Map',
data: 'MapInfo.mapHierarchyString',
}, {
title: 'Addresse MAC',
data: 'macAddress',
}],
initComplete: function(json) {
let returned_data = json;
//..Do something with data returned
}
});
});
Appreciate any help.
Just adding something to #Fawaz Ibrahim's answer, it's also better to add error option in Ajax call in order to check if you face any error or problem , because in case of error, dataSrc callback won't run, so you won't have any successful returned data.
ajax: {
...
dataSrc: function ( receivedData ) {
console.log('The data has arrived'); // Here you can know that the data has been received
return receivedData;
},
error: function (xhr, error, thrown) {
console.log('here you can track the error');
}
}
As it is mentioned on their official site:
For completeness of our Ajax loading discussion, it is worth stating
that at this time DataTables unfortunately does not support
configuration via Ajax. This is something that will be reviewed in
future
But you can use the idea of datasrc, like this:
$(function() {
$('#data-table').DataTable({
...
ajax: {
...
dataSrc: function ( receivedData ) {
console.log('The data has arrived'); // Here you can know that the data has been received
return receivedData;
}
},
...
});
});

ajax request - update record without form

To do a record update I usually use a CRUD and a store like this:
storeId: 'storeId',
model: 'model',
pageSize: 10,
autoLoad: true,
proxy: {
type: 'ajax',
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
},
api: {
create: 'php/crud.php?action=create',
read: 'php/crud.php?action=read',
update: 'php/crud.php?action=update',
destroy: 'php/crud.php?action=destroy'
},
reader: {
type: 'json',
rootProperty: 'net',
totalProperty: 'total',
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true,
encode: true,
rootProperty: 'net'
}
}
Logic for the update:
var record = form.getRecord();
record.set(values);
store.sync({
success: function () {
},
failure: function () {
},
callback: function () {
},
});
Problem: just change the value of a database column: YES / NO
Instead of removing a record with 'destroy', I want to just disable it with 'update' a database table column form NO to YES.
In this case I have no form; just a delete button.
I tried without success:
store.proxy.extraParams = {
sub_case: 'change_delete_state',
id_lista: id_lista
},
store.sync({
success: function () {
},
failure: function () {
},
callback: function () {
},
});
And:
Ext.Ajax.request({
url: 'php/crud.php?action=update',
params: {
sub_case: 'change_delete_state',
id_lista: id_lista
},
success: function () {
store.commitChanges();
},
failure: function () {
},
callback: function () {
},
});
I would appreciate suggestions to solve this problem.
EDITED:
Solved like this:
api: {
destroy: 'php/crud.php?action=destroy'
},
cliente-side logic:
// soft delete
store.proxy.extraParams = {
sub_case: 'change_delete_state',
id_lista: id_lista
},
//or
// hard delete
store.proxy.extraParams = {
id_lista: id_lista
},
store.remove(record);
store.sync({...});
server-side (PHP):
case "destroy":{
$record = stripslashes($_POST['net']);
$data = json_decode($record);
$id_lista = $data->{'id_lista'};
if($_REQUEST['sub_case'] == "change_delete_state"){
$sqlQuery = "UPDATE ...";
(...)
}else{
$sqlQuery = "DELETE ...";
(...)
}
}
You are well off if you hide the database logic on the server-side as far as possible.
So, if you only have one way to get rid of a record in the front-end, and the record should be removed from the store, you would just exchange the destroy api of that one "special" store with a special api:
api: {
create: 'php/crud.php?action=create',
read: 'php/crud.php?action=read',
update: 'php/crud.php?action=update',
destroy: 'php/crud.php?action=hide' // hide the record using a SQL update, and remove it from the client-side store; don't remove from server
},
Of course you would have to insert special logic into the crud.php to do the special processing on action=hide.
If you want to have two different ways, one for a "hard delete" and one for a "soft delete", but both should be removed from the store, things become a bit more complicated. You would then need a special boolean "flag" in your record that is processed server-side.
E.g.
fields:[{
name:'hardDelete',
type:'bool',
defaultValue:false
}]
and then you would do sth. along
if(hardDelete) record.set("hardDelete",true);
store.remove(record);
store.sync(
and on the server side you would have to read that flag and act according to its value.

paging not moving to new data in kendogrid

Please note that at this time I am new to ASP.NET MVC, JavaScript and Kendo. The Kendo grid paging works for the first 500 records returned, but won't allow paging to download more data from the server past 500. Here is my controller:
public ActionResult ExecuteTestRule(string ruleId, string ruleSql, string uwi, List<PdsMatchRuleParam> parameters = null)
{
if (Request.Url != null)
{
var query = PaginationQuery.Parse(Request.QueryString);
var upperLimit = query.FromUpper;
var lowerLimit = query.FromLower;
var dataSource = new MatchDataSource();
List<DataAccess.DbParameter> dbParameters = null;
var generatedSql = dataSource.GenerateQuerySql(ruleId, ruleSql, uwi, parameters, out dbParameters);
var results = dataSource.ExecuteTestRule(ruleId, generatedSql, dbParameters, upperLimit, lowerLimit).Select(u => new { UWI = u });
var response = new Dictionary<string, object>();
response["result"] = results;
response["rowCount"] = MatchDataSource.GetRowCount(generatedSql, dbParameters);
return Json(response, JsonRequestBehavior.AllowGet);
}
return null;
}
Here are the total number of rows available "rowCount" in the controller:
MatchDataSource.GetRowCount(generatedSql, dbParameters)
91637
Here is the Request.QueryString in the controller:
Request.QueryString
{}
[System.Web.HttpValueCollection]: {}
base {System.Collections.Specialized.NameObjectCollectionBase}: {}
AllKeys: {string[0]}
Pressing this button has no effect:
Here is my JavaScript code:
function bindTestRuleResults() {
PageState.Selected.Old.TestRuleResult = PageState.Selected.TestRuleResult;
var dataSource = new kendo.data.DataSource({
pageSize: 500,
data: PageState.Selected.TestRuleResult,
serverPaging: true
});
Grids.TestRuleResultsGrid.setDataSource(dataSource);
PageState.Selected.TestRuleResult = null;
}
function initTestRuleResultsGrid() {
$(IDS.testRuleResultsGrid).kendoGrid({
autoBind: true,
filterable: false,
navigatable: true,
pageable: {
refresh: true,
pageSizes: [10, 50, 100, 500],
buttonCount: 5
},
scrollable: true,
selectable: true,
serverFiltering: false,
serverPaging: true,
serverSorting: true,
sortable: false,
columns: [
{ field: "UWI", title: "UWI", width: "100%", attributes: { tabindex: "1" } }
],
change: function() {
var selectedDataItem = this.dataItem(this.select());
if (PageState.Selected.TestRuleResult !== selectedDataItem.TestRuleResult) {
PageState.Selected.TestRuleResult = selectedDataItem.TestRuleResult;
testRuleResultsSelectionChanged();
}
},
editable: false
});
// Add vertical scroll bars
$(IDS.testRuleResultsGrid + " .k-grid-content").css({
"overflow-y": "scroll"
});
Grids.TestRuleResultsGrid = $(IDS.testRuleResultsGrid).data('kendoGrid');
}
function execTestRule(uwi) {
$.ajax({
type: 'POST',
url: "ExecuteTestRule",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
ruleId: PageState.Selected.RuleId,
ruleSql: PageState.SqlEditor.RuleSql.getValue(),
uwi: "'" + uwi + "'",
parameters: PageState.RuleParameters
}),
schema: {
errors: function(response) {
return response.error;
},
data: function(response) {
return response.result;
},
total: function(response) {
return response.rowCount;
}
},
success: function(matchedUwiList) {
PageState.TestRuleResult = matchedUwiList.result;
var dataSource = new kendo.data.DataSource({
pageSize: 500,
data: matchedUwiList.result,
serverPaging: true
});
Grids.TestRuleResultsGrid.setDataSource(dataSource);
PageState.Selected.ChildUwi = null;
updateButtonStates();
},
error: function(e) {
var errorObject = JSON.parse(e.xhr.responseText);
var errorMessage = errorObject.Message;
//clear old error message
Grids.TestRuleResultsGrid.clearErrorMessage("error-message");
// add new error message
Grids.TestRuleResultsGrid.addErrorMessage("error-message", errorMessage);
}
});
}
It clearly has serverPaging = true in the data source. What am I missing? Do I need to somehow make pageSize dynamic in my JavaScript code? TIA.
UPDATE:
Thank you for the feedback, #Brett. This is how I've simplified the code as you suggested. How do I remove the success: function outside of the ajax part?
function execTestRule(uwi) {
$.ajax({
type: 'POST',
url: "ExecuteTestRule",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
ruleId: PageState.Selected.RuleId,
ruleSql: PageState.SqlEditor.RuleSql.getValue(),
uwi: "'" + uwi + "'",
parameters: PageState.RuleParameters
}),
success: function(matchedUwiList) {
PageState.TestRuleResult = matchedUwiList.result;
var dataSource = new kendo.data.DataSource({
schema: {
data: 'results',
total: 'rowCount'
},
pageSize: 500,
serverPaging: true
});
Grids.TestRuleResultsGrid.setDataSource(dataSource);
PageState.Selected.ChildUwi = null;
updateButtonStates();
}
});
}
When the execTestRule function is run, this is the error I'm getting:
You code is confusing to me, but I do see one particular problem. You are not telling the Kendo UI DataSource where your data and row count properties are in the returned object from your controller.
In your controller, you specify that the data is located in the response["results"] property, while the row count is in the response["rowCount"] property. Therefore, your returned object looks like this:
{
results: [...],
rowCount: 91637
}
The Kendo UI DataSource object's schema, by default, expects data to be located in a "data" property and the row count (a.k.a. number of items in data) to be located in the "total" property. Since your object does not conform to convention, you need to tell the data source that your properties are named differently.
var dataSource = new kendo.data.DataSource({
schema: {
data: 'results',
total: 'rowCount'
},
pageSize: 500,
serverPaging: true
});
So, you might say you are doing that already, but look where you defined it. You defined it on the $.ajax() call. That is not correct. The $.ajax() function does not care about schema. The Kendo UI DataSource does.
Kendo UI DataSource API reference
jQuery $.ajax API reference
As #Brett explained, resolved the problem by taking the schema out of the $.ajax() call. Also, started using a transport in the dataSource:
$.widget("myViewGrid", {
// ...
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "{0}/ViewDataById".format(options.controllerUri),
type: "get",
dataType: "json",
data: {
viewId: view.viewId,
Id: options.Id
}
}
},
schema: {
data: "mydata",
total: "total",
model:dataSourceModel
},
pageSize: view.pageSize,
serverPaging: true,
serverSorting: true,
serverFiltering: true
});
// ...
});

Persist additional dataSource.read parameters on paganation in Kendo data grid

I have a Kendo Grid that loads data via ajax with a call to server-side ASP.NET read method:
public virtual JsonResult Read(DataSourceRequest request, string anotherParam)
In my client-side JS, I trigger a read when a button is clicked:
grid.dataSource.read( { anotherParam: 'foo' });
grid.refresh();
This works as expected, only I lose the additional param when I move through the pages of results in the grid, or use the refresh icon on the grid to reload the data.
How do I persist the additional parameter data in the grid?
I have tried setting
grid.dataSource.data
directly, but without much luck. I either get an error if I pass an object, or no effect if I pass the name of a JS function that returns data.
if you want to pass additional parameters to Read ajax datasource method (server side), you may use
.DataSource(dataSource => dataSource
...
.Read(read => read.Action("Read", controllerName, new { anotherParam= "foo"}))
...
)
if you want to pass additional parameters through client scripting you may use datasource.transport.parameterMap, something as below
parameterMap: function(data, type) {
if (type == "read") {
return { request:kendo.stringify(data), anotherParam:"foo" }
}
Use the datasource.transport.parameterMap
parameterMap: function(data, type) {
if (type == "read") {
return kendo.stringify(data, anotherParam);
}
I'm not sure where your other param is coming from, but this is generally how I send extra parameters to the server.
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.parameterMap
if use datasource object :
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Api/GetData',
contentType: "application/json; charset=utf-8", // optional
dataType: "json",
data: function () {
return {
additionalParam: value
};
}
},
//parameterMap: function (data, type) {
// and so use this property to send additional param
// return $.extend({ "additionalParam": value }, data);
//}
},
schema: {
type: "json",
data: function (data) {
return data.result;
},
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
and set options in grid:
$("#grid").kendoGrid({
autoBind: false,
dataSource: dataSource,
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
]
});
and in click event this code :
dataSource.read();
and in api web method this action:
[HttpGet]
public HttpResponseMessage GetData([FromUri]KendoGridParams/* define class to get parameter from javascript*/ _param)
{
// use _param to filtering, paging and other actions
try
{
var result = Service.AllCustomers();
return Request.CreateResponse(HttpStatusCode.OK, new { result = result });
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, new { result = string.Empty });
}
}
good luck.
To persist the updated value of the additional parameter through pagination, you will need to create a global variable and save the value to it.
var anotherParamValue= "";//declare a global variable at the top. Can be assigned some default value as well instead of blank
Then, when you trigger the datasource read event, you should save the value to the global variable we created earlier.
anotherParamValue = 'foo';//save the new value to the global variable
grid.dataSource.read( { anotherParam: anotherParamValue });
grid.refresh();
Now, this is important. In your datasource object transport.read.data must be set to use a function as shown below:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Api/GetData',
contentType: "application/json; charset=utf-8", // optional
dataType: "json",
//Must be set to use a function, to pass dynamic values of the parameter
data: function () {
return {
additionalParam: anotherParamValue //get the value from the global variable
};
}
},
},
schema: {
type: "json",
data: function (data) {
return data.result;
},
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
Now on every page button click, you should get the updated value of the anotherParam which is currently set to foo

Backbone + kendoGrid, PUT not working

I'm trying to integrate kendoGrid on a Backbone View, this is my view code:
App.Views.UsersManager = Backbone.View.extend({
tagName: 'section',
id: 'users-manager',
className: 'tile',
template: Handlebars.compile($('#profile-usersManager-template').html()),
render: function () {
console.log('usersManager.render -> collection', this.collection);
var self = this;
this.$el.html(this.template());
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/users',
type: 'GET',
dataType: 'json'
},
update: {
url: '/users',
type: 'PUT',
dataType: 'json'
}
},
schema: {
data: 'data'
},
batch: true
});
this.$('table.users-manager').kendoGrid({
scrollable: false,
sortable: true,
dataSource: dataSource,
toolbar: ["save"],
editable: true,
navigatable: true,
// filterable: true,
});
return this;
}
});
The view render correctly, and the kendoGrid correctly GET my users data from my SlimPHP framework, but when i try to modify an element of the grid and hit the "Save Changes" button provided by "toolbar: ["save"]", nothing happens, even on my firebug console... there's no server communication at all.
I'm new on kendo (and Backbone also) development, maybe i'm failing something on the syntax? :stuck:
Update after Atanas Korchev answer
this is my DataSource updated:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/users',
type: 'GET',
dataType: 'json'
},
update: {
url: '/users',
type: 'PUT',
dataType: 'json'
}
},
schema: {
data: 'data',
model: {
id: 'id',
fields: {
email: {},
name: {},
surname: {},
rank: {},
type: {}
}
}
},
batch: true
});
That not solve my issue, i wanna notice that my php code look like that actually:
$app->put('/users', function () use ($app, $db) {
exit('put ok');
});
Just to see if the client/server communication works... I know it will be an error, but I can't see any firebug error too, like the "Save Changes" button has no event... (I will try the Dennis Rongo suggestion.. but I dont think is the solution...)
Sorry for my bad english
Try describing your model in the DataSource settings:
schema: {
data: 'data',
model: {
id: "MyId"
}
}
You need to at least specify the id.
Solved by removing the data: 'data' from the schema object, there's the link kendoGrid batch editing!

Categories