I'm using KendoGrid to display some data fetched from my service.
The user selects some parameters (company and date) and cliks on a load button.
The user selects a month on a datePicker and the server will return data from that date plus 11 months.
I only display the grid after the user click on the load button.
Load function:
function loadGrid(e) {
var companyIds = [1, 3, 7]; // user select it
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var rowHeaders = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
var _dataSource = function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: URL,
dataType: "json",
data: {
companyIds: companyIds,
date: kendo.toString(picker.value(), "yyyy-MM-dd") // user select it
}
}
},
schema: {
data: function (data) {
// function to handle data returned from server
var dataArray = [];
var index = 0;
for (var key in data[0]) {
if (Object.prototype.hasOwnProperty.call(data[0], key)) {
var property = key;
if (property == "date") {
continue;
}
key = {};
key["X"] = rowHeaders[index];
index++;
for (var i = 0; i < data.length; i++) {
var date = data[i].date;
var dateSplit = date.split("-");
var year = dateSplit[0];
var month = months[dateSplit[1] - 1];
var header = month + "_" + year;
key[header] = data[i][property];
}
dataArray.push(key);
}
}
return dataArray;
}
}
});
return dataSource;
};
$("#grid").kendoGrid({
scrollable: false,
editable: false,
dataSource: _dataSource()
});
}
When I click on the load button for the first time, the datasource is loaded and the grid is displayed correctly.
But, for instance, if I change the date on the datePicker and click on the load button again, the datasource is loaded with the correct data (new records for other months), but the grid is not refreshed.
If the first time I select the month Jan/2015, it loads and displays from Jan/2015 until Dec/2015, which is correct.
But if than I select the month Feb/2015, the datasource loads from Feb/2015 until Jan/2016 (correct), but the grid display the columns from Jan/2015 until Dec/2015, which is wrong. In this case, the column Jan/2015 is shown empty and the column Jan/2016 is not displayed.
Can someone point me to the right direction?
Thanks!
You should use a function for your dataSource -> transport -> read -> data:
data: function() {
return {
companyIds: companyIds,
date: kendo.toString(picker.value(), "yyyy-MM-dd") // user select it
};
}
UPDATE:
Here is how I would do it:
function loadGrid(e) {
$("#grid").data("kendoGrid").dataSource.fetch();
}
function getData() {
var companyIds = ...
var picker = ...
return {
companyIds: companyIds,
date: kendo.toString(picker.value(), "yyyy-MM-dd") // user select it
};
}
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: URL,
dataType: "json",
data: getData
}
},
schema: {
data: function (data) {
// function to handle data returned from server
var dataArray = [];
var index = 0;
for (var key in data[0]) {
if (Object.prototype.hasOwnProperty.call(data[0], key)) {
var property = key;
if (property == "date") {
continue;
}
key = {};
key["X"] = rowHeaders[index];
index++;
for (var i = 0; i < data.length; i++) {
var date = data[i].date;
var dateSplit = date.split("-");
var year = dateSplit[0];
var month = months[dateSplit[1] - 1];
var header = month + "_" + year;
key[header] = data[i][property];
}
dataArray.push(key);
}
}
return dataArray;
}
}
});
$("#grid").kendoGrid({
scrollable: false,
editable: false,
dataSource: dataSource
});
I ended up destroying and recreating the grid when the user clicks on load button.
$("#loadButton").kendoButton({
click: loadGrid
});
var loaded = false;
function loadGrid(e) {
if (value) {
if (loaded) {
var grid = $("#grid").data("kendoGrid");
grid.wrapper.empty();
grid.destroy();
}
$("#grid").kendoGrid({
scrollable: false,
editable: false,
autoBind: false,
dataSource: _dataSource()
});
$("#grid").data("kendoGrid").dataSource.read();
loaded = true;
} else {
e.preventDefault();
alert("aaaa");
}
}
Related
Hi I am trying to display some data in a kendo UI bar chart , the data comes from an ASP.NET MVC action that returns json data.
Is it possible to pass a function to a kendo UI data element like the following ?
series: [{
name: "Oddo Avenir Euro CI-EUR",
data: GetFundPerfCalendSP,
border: {
width: 0
}
The function :
function GetFundPerfCalendSP(){
$(document).ready(function(){
var data;
var value = $("#idProduitSP").text();
var bechmarkArray = new Array();
var SpArray = new Array();
console.log(value);
$.ajax({
url:'../controllerName/actionname',
type:'POST',
datatype:'json',
data:{
idProduitSP:value
},
success :function(result)
data = result;
for(var i = 0; i < data.length; i++) {
SpArray.push(data[i].PerformanceSP*100);
}
console.log(SpArray);
return SpArray;
},
error:function(error){
console.log("ajax request failed");
}
});
});
}
in my SAPUI5 app I am using a Multi Input Field with tokens which are bound to a JSON Model. Newly added entries are saved in the JSON Model. However, when deleting a token by pressing the "x" next to the token text, the token disappears from the multi input field. But when adding a new token the deleted one reappears.
How can I ensure that the deleted entry is also deleted from the JSON Model?
This is my current code for adding the token to the model:
multiInputField.addValidator(function(args){
MessageBox.confirm("Do you really want to add Token\"" + args.text + "\"?", {
onClose: function(oAction) {
if (oAction === MessageBox.Action.OK){
var oToken = new Token({key: args.text, text: args.text});
args.asyncCallback(oToken);
var aFields = sap.ui.getCore().getView().getModel("myModel").getProperty("/Tokens");
var oNewFields= {
Tokens: args.text
};
aFields .push(oNewFields);
sap.ui.getCore().getView().getModel("myModel").setProperty("/Tokens", aFields );
sap.ui.getCore().getView().getModel("myModel").refresh();
} else {
args.asyncCallback(null);
}
},
title: "Add Token"
});
return sap.m.MultiInput.WaitForAsyncValidation;
});
I guess we can use "tokenUpdate" event for this.
For example, given that I have this MultiInput in my view:
<MultiInput width="500px" id="multiInput" suggestionItems="{ path: 'dataModel>/data'}" showValueHelp="true" tokenUpdate="onTokenUpdate">
<core:Item key="{dataModel>key}" text="{dataModel>value}"/>
</MultiInput>
then in my controller I can handle this like :
onTokenUpdate: function(oEvent) {
var sType = oEvent.getParameter("type");
if (sType === "removed") {
var sKey = oEvent.getParameter("removedTokens")[0].getProperty("key");
var oModel = this.getView().getModel("dataModel");
var aData = this.getView().getModel("dataModel").getProperty("/data");
for (var i = 0, len = aData.length; i < len; i++) {
var idx;
console.log(sKey + "-" + aData[i].key);
if (aData[i].key === sKey) {
idx = i;
}
}
aData.splice(idx, 1);
oModel.setProperty("/data", aData);
console.log(oModel);
}
}
And this is my json:
{
"data": [
{
"key": "token1",
"value": "token1"
},
{
"key": "token2",
"value": "token2"
}
]
}
Here's what my chart displays:
Here's my Position tables:
My position table
cant really seem to figure out whats the problem.
-Ive got a button and a dropdown, when an item is selected from the dropdown and button is selected an orgchart must be displayed. The chart displays but the problems are:
-orgchart splitting into three charts
-And it keeps showing some Id's
-here's my code:
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$("#btnGetOrganogram").on('click', function (e) {
debugger
$ddlDepOrgano = $('[id$="ddlDepOrgano"]').val();
if ($ddlDepOrgano != "") {
var jsonData = $.ajax({
type: "POST",
url: '/services/eleaveService.asmx/GetChartData',
data: "{'depid':'" + $ddlDepOrgano + "'}",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: OnSuccess_getOrgData,
error: OnErrorCall_getOrgData
});
function OnSuccess_getOrgData(repo) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
var response = repo.d;
for (var i = 0; i < response.length; i++) {
var row = new Array();
var Pos_Name = response[i].Pos_Name;
var Pos_Level = response[i].Pos_Level;
var Emp_Name = response[i].Emp_Name;
var Pos_ID = response[i].Pos_ID;
var Emp_ID = response[i].Emp_ID;
data.addRows([[{
v: Emp_ID,
f: Pos_Name
}, Pos_Level, Emp_Name]]);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data,{ allowHtml: true });
}
function OnErrorCall_getOrgData() {
console.log("something went wrong ");
}
} else {
bootbox.alert("Invalid Department Name please try again.");
}
e.preventDefault();
});
}
according to the data format, Column 1 should be the ID of the manager, which is used to build the tree...
Column 1 - [optional] The ID of the parent node. This should be the unformatted value from column 0 of another row. Leave unspecified for a root node.
looking at the data table image posted, this should be in column --> Mngr_ID
as such, recommend the following changes when loading the data...
for (var i = 0; i < response.length; i++) {
var row = new Array();
var Pos_Name = response[i].Pos_Name;
var Emp_Name = response[i].Emp_Name;
var Emp_ID = response[i].Emp_ID;
var Mngr_ID = response[i].Mngr_ID;
data.addRow([
{
v: Emp_ID,
f: Pos_Name
},
Mngr_ID,
Emp_Name
]);
}
I want to label xaxis with values from JSON data that is happening but it is printing it at wrong place as shown in screenshot :
Here only seven values are present its labeled in that manner but actual data is plotted by leaving a gap of one. For example at 11th there is value and then again at 13t so total seven values but taking 14 places and label properly taking there first seven places how to match labels and bar graph
Following is my code snippet :
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(key);
volumes.push(key);
my_data_list.push('Average Latency', parseInt(avg_latency));
my_data_list1.push('Read Latency', parseInt(read_latency));
my_data_list2.push('Write Latency', parseInt(write_latency));
}
$('#graphcontainer3').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Volume Level Latency'
},
yAxis: {
tickInterval: 100,
title: {
text: 'Latency(ms)'
}
},
xAxis: {
categories: volumes,
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} ms</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 2
}
},
series: [{
name: 'Average latency',
data: my_data_list,
}, {
name: 'Read Latency',
data: my_data_list1,
}, {
name: 'Write Latency ',
data: my_data_list2,
}]
});
Can anyone help me in this code to make this work fine???
I rectified the problem by myself :) It just I was giving labels two times
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list3 = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(avg_latency);
volumes.push(key);
my_data_list3.push(parseInt(avg_latency)); //here no need to give label again as it is done my volume(key)
my_data_list1.push( parseInt(read_latency));
my_data_list2.push(parseInt(write_latency));
}
This is what I was expecting as output .Hope it might be helpful for someone else hence answered.
I want to slice a JSON array, but get the following error:
Object # has no method 'slice'
The following is my code:
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
programService.query({
id: $routeParams.id
}, function (result) {
data = {
'program': result
};
data = JSON.stringify(data);
data = JSON.parse(data);
$scope.setPagingData(data,page,pageSize);
});
}, 100);
};
$scope.setPagingData = function(data, page, pageSize){
var pagedData = data.slice(0, 3);
$scope.myData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
JSON data:
{programId:1,
programName:project1,
programContent:content1,
programStartDate:2012-01-01,
templateId: '1'}
I want to slice the array as follows: programId, 1, programName, project1, ...
I am so confused , please help.
Try
var data = {
programId:1,
programName:'project1',
programContent:'content1',
programStartDate:'2012-01-01',
templateId: '1'
}
var array = [];
for(var key in data){
if(!data.hasOwnProperty(key)){
continue;
}
array.push(key, data[key])
}
console.log(array, array.slice(0, 4))