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");
}
});
});
}
Related
I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>
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'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");
}
}
I wanted reload a core-list element to show new data, but it´s not refreshing.
I re-call the JS function thats generate the data but doesn t work... and reload like a 'normal' div doesn t work either! The list only shows the new data if i reload the entire page...
function values(sender, textomsg, datacriacao, senderfoto){
var sender2 = sender.split(",");
var textomsg2 = textomsg.split(",");
var datacriacao2 = datacriacao.split(",");
var senderfoto2 = senderfoto.split(",");
var namegen = {
generateString: function (inLength) {
var s = '';
for (var i = 0; i < inLength; i++) {
s += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
return s;
},
generateName: function (inMin, inMax) {
return this.generateString(Math.floor(Math.random() * (inMax - inMin + 1) + inMin));
}
};
Polymer('list-test', {
count: sender.length,
ready: function () {
this.data = this.generateData();
},
generateData: function () {
var names = [], data = [];
for (var i = 0; i < this.count; i++) {
names.push(namegen.generateName(4, 8));
}
names.sort();
for (var i = 0; i < this.count; i++) {
data.push({
index: i,
sender: sender2[i],
textomsg: textomsg2[i],
datacriacao: datacriacao2[i],
senderfoto: senderfoto2[i]
});
}
return data;
},
tapAction: function (e) {
console.log('tap', e);
}
});
}
<%----%>
<template id="templateConversas" runat="server">
<div id="item" class="item {{ {selected: selected} | tokenList }}" ><%--onClick="conversa('{{name}}');"--%>
<div class="message" style="background-image: url({{senderfoto}});">
<span class="from"><br/>{{sender}}</span>
<span class="timestamp">{{datacriacao}}</span>
<div class="subject"><br/>{{textomsg}} </div><%--------Infinite List. {{index}}--%>
<%--<div class="body"><br/>Mensagem de teste...........</div>--%>
</div>
</div>
</template>
The problem is also reload the 'list-test'. if i call the js function after the list is loaded it doesn't apply the new data...
Your code isn't complete so it is hard to understand but I think that the problem is that you don't assign the result of the generateData() function to the template's model. Try following script for your component
Polymer('list-test', {
created: function () {
this.data = [];
},
refresh: function () {
this.data = this.generateData();
},
generateData: function () {
// your original code here
}
});
Now the list content should be updated with newly generated data when you call refresh() of the list-test element. To fill the list when element is created add
ready: function () {
this.refresh();
},
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))