highcharts - drilldown: does not workn with AJAX - ajax

I have a chart below that does not work with AJAX request.
function ajaxGraficoBarraUnidade() {
var strSeries = "";
var strDrilldown = "";
$.ajax({
type: "POST",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "ajaxBlitzCarregamentoGrafico.php",
beforeSend: function () {
},
success: function (strRetorno) {
strSeries = strRetorno.geos;
strDrilldown = strRetorno.unidades;
carregaGraficoBarraUnidade(strSeries, strDrilldown);
},
error: function (txt) {
}
});
}
function carregaGraficoBarraUnidade(strSeries, strDrilldown) {
$('#divGraficoBarraUnidade').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: strSeries,
drilldown: {
series: strDrilldown
}
});
</code>
I have a return equal to ajax below:
{'geos':[{'name': 'Regionais','data': [{'name':'Geo CO','y':1.59,'drilldown':'Geo CO'},{'name':'Geo MG/ES','y':4.41,'drilldown':'Geo MG/ES'},{'name':'Geo NE','y':3.35,'drilldown':'Geo NE'},{'name':'Geo NO','y':1.96,'drilldown':'Geo NO'},{'name':'Geo PR/SPI','y':0.10,'drilldown':'Geo PR/SPI'},{'name':'Geo RJ','y':1.81,'drilldown':'Geo RJ'},{'name':'Geo RS/SC','y':0.75,'drilldown':'Geo RS/SC'},{'name':'Geo SPC','y':0.33,'drilldown':'Geo SPC'}]}], 'unidades':[{'name':'Geo CO','id':'Geo CO','data': [['CDC Araguaina',1.30],['CDC Catalao',0.01],['CDC Formosa',4.70],['CDC Porto Velho',0.29],['CDC Rio Branco',0.00],['CDC Rio Verde',0.12],['CDC Rondonopolis',5.15],['CDC Tangara',0.51],['CDD Brasilia',0.06],['CDD Brasilia Int',2.67],['CDD Caceres',0.05],['CDD Campo Gde',0.00],['CDD Cuiaba Int',0.03],['CDD Goiania Int',0.00],['CDD Itumbiara',38.19],['CDD Manaus',0.43]]},{'name':'Geo MG/ES','id':'Geo MG/ES','data': [['CDD Alfenas',0.02],['CDD Cachoeiro',0.28],['CDD Ipatinga',0.03],['CDD João Monlevade DDC',0.00],['CDD Minas Int',0.77],['CDD Poços de Caldas',0.91],['CDD Pouso Alegre',0.17],['CDD Uberaba',0.08],['CDD Uberlandia',0.07],['CDD Vitoria',25.62],['CDL AS Minas',0.01],['CDL Santa Luzia',2.70]]},{'name':'Geo NE','id':'Geo NE','data': [['CDC Arapiraca',0.12],['CDC Lapa',0.32],['CDD Aracaju',0.05],['CDD Caruaru',8.05],['CDD F. de Santana',0.17],['CDD Guanambi',0.01],['CDD Ilheus',0.03],['CDD Maceio',0.06],['CDD Olinda',0.16],['CDD Rib. Pombal',0.04],['CDD Salvador',0.17],['CDD Vit. da Conquista',0.06],['CDL Cabo',1.33],['CDL Jequie',0.06]]},{'name':'Geo NO','id':'Geo NO','data': [['CDD Aracati',0.02],['CDD Balsas',0.08],['CDD Belem',0.02],['CDD Campina Grande',0.03],['CDD Fortaleza',0.03],['CDD Imperatriz',0.02],['CDD Joao Pessoa Int',5.86],['CDD Maranhao Int ',12.72],['CDD Natal Int',0.02],['CDD Sul Maranhão',0.03],['CDL Ceara',0.37]]},{'name':'Geo PR/SPI','id':'Geo PR/SPI','data': [['CDC Beltrao',0.00],['CDD Agudos Int',0.12],['CDD Araçatuba',0.07],['CDD Araraquara',0.02],['CDD Bebedouro',0.09],['CDD Curitiba',0.00],['CDD Jaú',3.19],['CDD Londrina',0.00],['CDD Mogi Mirim',0.04],['CDD Ponta Grossa',0.37],['CDD Presidente Prudente',0.05],['CDD Rib. Preto',0.04],['CDL Paranagua',0.02]]},{'name':'Geo RJ','id':'Geo RJ','data': [['CDD Campos',1.18],['CDD Jacarepagua',1.65],['CDD Niteroi',0.02],['CDD Nova Friburgo',0.01],['CDD Nova Iguacu',0.02],['CDD Petropolis',0.00],['CDD RJ Campo Gde Int',3.77],['CDD S. Cristovao',0.81],['CDL Itaperuna',0.14]]},{'name':'Geo RS/SC','id':'Geo RS/SC','data': [['CDD Blumenau',0.07],['CDD Camboriu',0.11],['CDD Caxias do Sul',0.07],['CDD Florianopolis',0.12],['CDD Pelotas',0.04],['CDD Porto Alegre',1.06],['CDD S. Cruz Sul',0.02],['CDD Santa Maria',0.45],['CDD Sapucaia Int',2.66]]},{'name':'Geo SPC','id':'Geo SPC','data': [['CDD Campinas',0.12],['CDD Diadema',0.72],['CDD Guarulhos',0.23],['CDD Jundiai',1.04],['CDD Litoral SP',0.05],['CDD Mooca',1.05],['CDD Norte',0.10],['CDD Oeste',0.04],['CDD Praia Grande',0.06],['CDD São José dos Campos',0.54],['CDD Sul SP',0.00],['CDD Taubaté',0.82],['CDD Votorantin',0.77]]}]}
It does not recognize the values passed in SERIES. I do not think the error. Does anyone know what might be happening? Tanks!

What might be happening is your data is getting loaded after the chart is created, so I've changed the format to be as shown in the Highcharts documentation, but tried not to change to much otherwise.
Highcharts documentation on working with data
See a plunkr demo with your chart working with available data
The data is hosted on myjson.com as JSON, so I changed the POST to a GET request.
Here is the key HTML code:
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="divGraficoBarraUnidade" style="width:100%; height:400px;"></div>
This is the Javascript / jQuery code:
$(function () {
$(document).ready(function() {
var options = {
chart: {
renderTo: 'divGraficoBarraUnidade',
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: {},
drilldown: {
series: {}
}
};
function ajaxGraficoBarraUnidade() {
$.ajax({
type: "GET",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "https://api.myjson.com/bins/42c59",
beforeSend: function () {
},
success: function (strRetorno) {
options.series = strRetorno.geos;
options.drilldown.series = strRetorno.unidades;
var chart = new Highcharts.Chart(options);
console.log('options', options)
},
error: function (txt) {
// Report errors here...
}
});
}
ajaxGraficoBarraUnidade();
});
});

Related

Kendo Scheduler Suggestions

I want to show day in shift for example 24 days hours can be divided into 3 shift 8 hours each or can 6 hours each.
Against that i wanted to add events in Kendo Scheduler. Each day must have shift as show in below image
in the image shift marked for each day and noted with different color.
Each shift can or can not have events.
I'm also expecting functionality where events can move across the shifts.
I believe you'll have to implement a custom view to accomplish this. Here is a Telerik page that demonstrates it, and if you click the "Open in Dojo" link in the upper right of the code example you can see it execute (and edit and try it yourself).
Code example for their custom 3-day view from link
<div id="scheduler"></div>
<script>
var CustomAgenda = kendo.ui.AgendaView.extend({
endDate: function() {
var date = kendo.ui.AgendaView.fn.endDate.call(this);
return kendo.date.addDays(date, 31);
}
});
var ThreeDayView = kendo.ui.MultiDayView.extend({
nextDate: function () {
return kendo.date.nextDay(this.startDate());
},
options: {
selectedDateFormat: "{0:D} - {1:D}"
},
name: "ThreeDayView",
calculateDateRange: function () {
// Create a range of dates that will be displayed within the view.
var start = this.options.date,
idx, length,
dates = [];
for (idx = 0, length = 3; idx < length; idx++) {
dates.push(start);
start = kendo.date.nextDay(start);
}
this._render(dates);
}
});
$(function() {
$("#scheduler").kendoScheduler({
date: new Date("2013/6/13"),
startTime: new Date("2013/6/13 07:00 AM"),
height: 600,
views: [
"day",
"week",
// "custom week",
{ type: "ThreeDayView", title: "Three day view", selected: true },
// "custom agenda",
{ type: "CustomAgenda", title: "Custom Agenda" }
],
timezone: "Etc/UTC",
dataSource: {
batch: true,
transport: {
read: {
url: "https://demos.telerik.com/kendo-ui/service/tasks",
dataType: "jsonp"
},
update: {
url: "https://demos.telerik.com/kendo-ui/service/tasks/update",
dataType: "jsonp"
},
create: {
url: "https://demos.telerik.com/kendo-ui/service/tasks/create",
dataType: "jsonp"
},
destroy: {
url: "https://demos.telerik.com/kendo-ui/service/tasks/destroy",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
schema: {
model: {
id: "taskId",
fields: {
taskId: { from: "TaskID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start" },
end: { type: "date", from: "End" },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
description: { from: "Description" },
recurrenceId: { from: "RecurrenceID" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
ownerId: { from: "OwnerID", defaultValue: 1 },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
}
}
});
});
</script>

How to get field value when edit data in Kendo Ui treelist

I'm new in Kendo UI,and i have a question. Now i'm use TreeList / Editing and how to auto load value to other field when i edit value to first field ?
example:
1.serial number: 123456789
2.name : test
when i edit serial number 123456789 to first field and auto load name to second field.
To set the value of column B based on change made to a column A, you need to edit the model bound to the tree list. For this do the following:-
Handle edit event of the tree list. On this save the model to a
local variable.
Add an editor
template
to column A. On the select event set the value of model.
Below is a working code snippet:-
<div id="treelist"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service";
var model= null;
var employeesData=[{"EmployeeId":101,"FirstName":"Daryl","LastName":"Sweeney"},
{"EmployeeId":202,"FirstName":"Guy","LastName":"Wooten"},
{"EmployeeId":303,"FirstName":"Priscilla","LastName":"Frank"},
{"EmployeeId":404,"FirstName":"Ursula","LastName":"Holmes"},
{"EmployeeId":505,"FirstName":"Anika","LastName":"Vega"}];
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/EmployeeDirectory/All",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
schema: {
model: {
id: "EmployeeId",
parentId: "ReportsTo",
fields: {
EmployeeId: { type: "number", nullable: false },
ReportsTo: { nullable: true, type: "number" },
FirstName: { validation: { required: true } },
HireDate: { type: "date" },
Phone: { type: "string" },
HireDate: { type: "date" },
BirthDate: { type: "date" },
Extension: { type: "number", validation: { min: 0} },
Position: { type: "string" }
},
expanded: true
}
}
});
$("#treelist").kendoTreeList({
dataSource: dataSource,
toolbar: [ "create", "save", "cancel" ],
editable: "incell",
height: 540,
dataBound: function (e) {
var items = e.sender.items();
for (var i = 0; i < items.length; i++) {
var dataItem = e.sender.dataItem(items[i]);
var row = $(items[i]);
if (dataItem.isNew()) {
row.find("[data-command='createchild']").hide();
}
else {
row.find("[data-command='createchild']").show();
}
}
},
edit: function(e) {
model = e.model;
},
columns: [{
field: "EmployeeId",
expandable: true,
title: "Serial Number",
width: 180,
editor: function(container, options) {
// create an input element
var input = $("<input/>");
// set its name to the field to which the column is bound ('lastName' in this case)
input.attr("name", options.field);
// append it to the container
input.appendTo(container);
// initialize a Kendo UI AutoComplete
input.kendoAutoComplete({
dataTextField: "EmployeeId",
dataSource: employeesData,
select: function(e) {
if(model !=null){
model.FirstName = e.dataItem.FirstName;
model.LastName = e.dataItem.LastName;
}
}
});
}
},
{ field: "FirstName", title: "First Name", width: 100 },
{ field: "LastName", title: "Last Name", width: 100 },
{ field: "Position", width: 100 },
{ field: "Phone", title: "Phone", width: 100 },
{ field: "Extension", title: "Ext", format: "{0:#}", width: 100 },
{ command: [{name: "createchild", text: "Add child"},"destroy" ], width: 240 }]
});
});
</script>
You can trigger your function when the row is being saved or when the edit field is being changed. Take a look at the list of events here and choose when exactly you want to make the changes. https://demos.telerik.com/kendo-ui/treelist/events
here is a example how to all a function when saving the changes: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist/methods/saverow
I´m not sure witch edit method you are using (inline, inCell or Popup edit mode) each method can use events like saveRow, beforeEdit...
Check all the events documentation here: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#events

How to restrict the check box check to 5 in Kendo UI grid

How to restrict the check box check to 5 in Kendo UI grid.
I am using Kendo UI grid with check box. I want to restrict check box selection to 5
Please find the code attached
$(function () {
$("#grid").kendoGrid({
dataSource: {
pageSize: 10,
transport: {
read: {
url: "url",
dataType: "json"
}
},
schema: {
model: {
id: "Id",
fields: {
Id: {
type: "string"
},
Title: {
type: "string"
},
OrderDate: {
type: "date",
defaultValue: null
}
}
}
}
},
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "Title", title: "Title" },
{ field: "OrderDate", title: "Order Date", format: "{0:MM/dd/yyyy}", encoded: true }
]
});
});
function onChange(arg) {
//console.log("The selected product ids are: [" + this.selectedKeyNames().join(", ") + "]");
}
Thanks in advance
This is tested code according your requirement only difference is that checkbox column created with template.
Reference link : https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Selection/grid-selection-checkbox
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.mobile.all.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.1.115/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<button id="showSelection">Show selected IDs</button>
<script>
$(document).ready(function () {
//DataSource definition
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
editable: false,
nullable: true
},
ProductName: {
validation: {
required: true
}
},
UnitPrice: {
type: "number",
validation: {
required: true,
min: 1
}
},
Discontinued: {
type: "boolean"
},
UnitsInStock: {
type: "number",
validation: {
min: 0,
required: true
}
}
}
}
}
});
//Grid definition
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
//define dataBound event handler
dataBound: onDataBound,
toolbar: ["create"],
columns: [
//define template column with checkbox and attach click event handler
{ template: "<input type='checkbox' class='checkbox' />" },
"ProductName", {
field: "UnitPrice",
title: "Unit Price",
format: "{0:c}",
width: "100px"
}, {
field: "UnitsInStock",
title: "Units In Stock",
width: "100px"
}, {
field: "Discontinued",
width: "100px"
}, {
command: ["edit", "destroy"],
title: " ",
width: "172px"
}
],
editable: "inline"
}).data("kendoGrid");
//bind click event to the checkbox
grid.table.on("click", ".checkbox" , selectRow);
$("#showSelection").bind("click", function () {
var checked = [];
for(var i in checkedIds){
if(checkedIds[i]){
checked.push(i);
}
}
alert(checked);
});
});
var checkedIds = {};
//on click of the checkbox:
function selectRow() {
//// *********Prevent to select more than 5 record*************************
if(Object.keys(checkedIds).length>=5)
{
this.checked=false;
}
/// **********************************
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem(row);
checkedIds[dataItem.id] = checked;
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
//on dataBound event restore previous selected rows:
function onDataBound(e) {
var view = this.dataSource.view();
for(var i = 0; i < view.length;i++){
if(checkedIds[view[i].id]){
this.tbody.find("tr[data-uid='" + view[i].uid + "']")
.addClass("k-state-selected")
.find(".checkbox")
.attr("checked","checked");
}
}
}
</script>
</body>
</html>
Let me know if you have questions or concerns.

Populate three highchart graphics with one ajax call

I am trying to figure out how to combine 3 ajax call into 1 but so far I didn't find out the correct way to do it. I have the following three highcharts:
chart1 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart1_div',
defaultSeriesType: 'spline',
events: {
load: GetData1(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart1',
color: "#6bd9ec", //37f312
data: chart1_data
}]
});
chart2 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart2_div',
defaultSeriesType: 'spline',
events: {
load: GetData2(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart2',
color: "#6bd9ec", //37f312
data: chart2_data
}]
});
chart3 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart3_div',
defaultSeriesType: 'spline',
events: {
load: GetData3(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart3',
color: "#6bd9ec", //37f312
data: chart3_data
}]
});
At the moment I am making three different ajax calls:
function GetData1(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat);
chart1_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData2(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val2));
});
chart2_div.xAxis[0].setCategories(cat);
chart2_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData3(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val3));
});
chart3_div.xAxis[0].setCategories(cat);
chart3_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
As you can see, I am right now making the same ajax call 3 times just to be able to populate the 3 charts differently. Does anyone know how could I generate exactly the same 3 charts but only make 1 ajax call? Thanks a lot
Something like:
function GetDataAll(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat1= [];
var ser1= [];
var cat2= [];
var ser2= [];
var cat3= [];
var ser3= [];
$.each(f.d, function (i, e) {
cat1.push(e.date);
ser1.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat1);
chart1_div.series[0].setData(ser1);
chart2_div.xAxis[0].setCategories(cat2);
chart2_div.series[0].setData(ser2);
chart3_div.xAxis[0].setCategories(cat3);
chart3_div.series[0].setData(ser3);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
Under the load event I could call GetData1(date) for the 3 charts but this way I will be hitting the ajax call 3 times. I am probably doing this the wrong way and must be a more efficient way. I will appreciate any thoughts, thank you so much
EDITED - LATEST UPDATE THAT WORKS BASED ON #WERGELD HELP
var chart1_options = {
chart: {
renderTo: 'chart1_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart1',
color: "#6bd9ec"
}]
};
var chart2_options = {
chart: {
renderTo: 'chart2_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart2',
color: "#6bd9ec"
}]
};
var chart3_options = {
chart: {
renderTo: 'chart3_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart3',
color: "#6bd9ec"
}]
};
function GetDataAll(date) {
$ajax({..
chart1_options.xAxis.categories = cat1;
chart1_options.series[0].data = ser1;
chart2_options.xAxis.categories = cat2;
chart2_options.series[0].data = ser2;
chart3_options.xAxis.categories = cat3;
chart3_options.series[0].data = ser3;
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chart1_options));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chart2_options));
var chart3 = new Highcharts.Chart(Highcharts.merge(options, chart3_options));
});
}
Here is some psuedo code to get you going. What you need to do is setup a chart option object that contains all the constant items among your charts:
var options = {
chart: {
height: 155,
defaultSeriesType: 'spline'
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
}
};
Next you do your ajax call and assign your series' data and title (and any other items) and create an object for each chart you want to create:
var chartOptions1 = {
chart: { renderTo: 'container1' },
series: []
};
var chartOptions2 = {
chart: { renderTo: 'container1' },
series: []
};
Next you do your code to get the chart data/name/etc that you want to have for each chart which I will not go into here. The next step is to then create your chart from the merged options:
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chartOptions1));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chartOptions2));
This should do it. Again, it is psuedocode but you get the idea. Global options + merge are you friends. Full psuedocode here.

How I write a dynamic URL in kendo UI DataSource like "update/{id}"

I have a web API. In that I wrote a update method. But it need to id of the table row to update to the row.
I use a grid to show data and use a toolbar to edit the row.
My question is how I pass that id to the update.
Can someone guide me ??
update: function(options) {
$.ajax( {
url: function(data) { return "updateUsuarios/"+data.Id,
dataType: "json",
.....
Well i suggest you, explain more your question, but i think this examples could help , if you have a toolbar as a template like this:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<button type="button" id="update">Update</button>
</div>
</script>
You "grid" need the attr "toolbar"
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
filterable:true,
toolbar: kendo.template($("#template").html()),
columns: [
{ field:"username", title: "Username" , width: "120px" },
{ field: "nombre", title:"Nombre", width: "120px" },
{ field: "apellido", title:"Apellido", width: "120px" },
{ field: "ci", title:"Documento de Identidad", width: "120px" },
{ field: "email", title:"Direccion de Correo", width: "120px" },
{ field: "activo",title:"Estatus", width: "120px" },
{ field: "fecha_caducidad",title:"Fin Demo", width: "120px",template: "#= kendo.toString(kendo.parseDate(fecha_caducidad, 'yyyy-MM-dd'), 'MM/dd/yyyy') #" },
{ field: "licencia_status",title:" ", width: "40px",template:'<img src="assets/images/#:data.licencia_status#.png"/>' },
{ command: ["edit"], title: " ", width: "120px" }],
editable: "popup",
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
selectable: true
});
So,you can configure a kendo button and add functionality in the event click:
$("#update").kendoButton({
click: function(){
//Here you will have the selected row
var self=$('#grid').data('kendoGrid')
var index = self.items().index(self.select());
var rowActual= self.dataSource.data()[index];
rowActual=self.dataItem(self.select());
if(rowActual==undefined || rowActual ==null) {
alert("No row selected");
}else{
$.ajax({
type: "POST",
url: "update",
data: {
id:rowActual.id
},
dataType: 'json',
success: function (data) {
},
error: function(){
}
});
}
}
});
and send in the ajax the row id, but if you are update the row with the inline edition you could try with a datasource like this
dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "readUsuarios",
dataType: "json",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: "updateUsuarios",
dataType: "json",
data: {
models: kendo.stringify(options.data.models)
},
success: function(data) {
// response server;
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
username: { editable: false, nullable: true },
nombre: { validation: { required: true } },
apellido: { type: "string", validation: { required: true} },
ci: { type: "string", validation: { required: true} },
email: { type: "string", validation: { required: true } },
activo: { type: "boolean",editable: false },
fecha_caducidad: { type: "date" },
licencia_status:{editable: false}
}
}
}
});
I hope this help!

Resources