can i check what is new data on sync?
i have this:
$('#order_it').click(function(){
gridNewData.sync(); // this will send data to server
});
gridNewData complete:
complete: function(xhr, textStatus) {
if (textStatus == 'success') {
orders.read(); // this will refresh orders, and grid too, a
gridNewData.data([]); // empty that temp datasource
}
}
and:
var orders = new kendo.data.DataSource({
autoSync: false,
transport: {
read: {
contentType: 'application/json',
url: '/dokument/orders/',
dataType: 'json',
complete: function(xhr, textStatus) {
// i think that here i need to get new synced items(or uids)
}
}
},
schema: {
model: {
id: 'id'
}
}
});
I need to make that rows in grid with another color, but can't find way to check what is new data.
You will not get new uid's neither the items. What you can do is to iterate through the collection of data before you call sync() and search for "isdirty".
Related
In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}
I currently have some ajax that sends an array to php for processing. The array size at most would be around 1000 elements which will be enough for the server to time out while the php is processing. I would like to chunk the array and send it in batched ajax requests (or maybe just one at a time) that will each finish without timing out.
Below is my basic code structure. I'm trying to use promises and iterate through the chunks:
Here's the basic structure of the working function (non-promise version):
function ajax_function(big_array) {
$.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array',
'array_to_process': big_array
},
beforeSend: function () {
xxx
},
dataType: 'json',
success: process_big_array_chunk_handler,
error: function (xhr, desc, err) {
console.log(xhr);
console.log('Details: ' + desc + '\nError: ' + err);
}
});
}
Here's work in progress trying to add the loop and promise.
function ajax_function(big_array) {
var big_array_chunks = make it into chunks somehow;
$.each(big_array_chunks, function (big_array_chunk) {
var request = $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array_chunk',
'array_to_process': big_array_chunk
},
dataType: 'json'
}).done(function (data) {
process_big_array_chunk_handler(data);
}).fail(function (xhr, desc, err) {
console.log(xhr);
console.log('Details: ' + desc + '\nError: ' + err);
});
});
}
Trying to get my head around how this all fits together:
each iteration of loop
responses from php
how to use my response handler when it's all done
fyi, this is being done within the context of WordPress if that matters.
Response to Bergi:
function ajax_function(big_array) {
var big_array_chunks = make big_array into chunks somehow;
var request = $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array_chunk',
'array_to_process': big_array_chunk
},
dataType: 'json'
}).then(function (data) {
process_big_array_chunk_handler(data);
});
}
The simplest solution I can think of is to just pre-chunk the array and then just use the .reduce() design pattern for serializing promises.
function processBigArray(bigArray, chunkSize) {
// pre-split array into chunks
var chunkArray = [];
for (var i = 0; i < bigArray.length; i+=chunkSize) {
chunkArray.push(bigArray.slice(bigArray, i, chunkSize));
}
var results = [];
// use .reduce() design pattern for chaining and serializing
// a sequence of async operations
return chunkArray.reduce(function(p, chunk) {
return p.then(function() {
return $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array',
'array_to_process': chunk
},
beforeSend: function () {
xxx
},
dataType: 'json',
}).then(function(data) {
results.push(data);
});
});
}, Promise.resolve()).then(function() {
// depending upon what your ajax returns, results might be an array of arrays
// that you would want to flatten
console.log(results);
return results;
});
}
// usage
processBigArray(someBigArray, 50).then(function(results) {
// process results here
}).catch(function(err) {
// deal with error here
console.log(err);
});
Am calling web api method from view model and getting the 10 records per click. I want paging for kendo template.
this is my code:
// this is the web api method which gets 10 records per each call
function WebApiMethod(parameter)
{
var url = webApiUrl + 'api/{controller}/{methodname}';
var success = function(result)
{
}
CallWebApi(url, 'POST', success, parameter);
}
///this is the ajax call that am calling from webapimethod
function CallWebApi(url, type, successCallBack, data) {
jQuery.support.cors = true;
$.ajax({
cache: false,
type: type,
url: url,
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: successCallBack,
error: function (xhr, err) {
}
});
}
///this is the kendo pager in which am biding the datasource
function KendoPager()
{
var pager = $("#pager").kendoPager({
dataSource: ViewModels["NameOfVM"].dataSource,
info: false,
change: function () {
ViewModels["NameOfVM"].pageIndex = pager.page();
}
}).data("kendoPager");
}
//this is the datasource am bind to kendopager
dataSource: new kendo.data.DataSource({
serverPaging:true,
pageSize:10,
})
Thanks in advance.
Is it possible to access and modify data in Kendo UI grid before updating?
Below is an example to illustrate what I need. The options.data contains the sent data but it is already formatted in string "models=%B7%22Id22%.... etc" not really convenient form.
dataSource = new kendo.data.DataSource({
transport: {
read: {
...
},
update: {
url: baseURL + "update",
beforeSend: function(xhr, options){
xhr.setRequestHeader('API-KEY', apikey );
var modifiedData = doSomething(options.data);
return modifiedData;
},
dataType: "json",
method: "POST",
dataFilter: function(data){
... some data recieved modification
return JSON.stringify(somedata);
},
complete: function(e) {
....
}
},
You should be able to use the parameterMap function, check the type for "update" and change the options.data anyway you want.
parameterMap: function(options, type) {
if(type === "update") {
options.someProperty = "somenewvalue";
}
return kendo.data.transports.odata.parameterMap(options, type);
}
I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '¬ificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.