Setting datasource of Kendo UI chart as well as showing the summary? - javascript

I am using ajax api calls for getting data from a SQL database as below:
function getJsonData(type, period1, period2, id) {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
url: createURL(type, period1, period2, id),
dataType: "json",
contentType: "application/json; chartset=utf-8"
}
},
});
return dataSource;
}
Using the above datasource, I am creating a Kendo chart as below:
function stepsChart(container, title, period1, period2) {
var dSource = getJsonData("Summary", period1, period2, "<% = id %>");
$(container).kendoChart({
dataSource: dSource,
seriesColors: ["orangered"],
chartArea: {
background: ""
},
title: {
text:title
},
legend: {
visible: false
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "column",
gap:5
},
series: [{
name: "steps",
field: "steps",
categoryField: "createddate",
aggregate: "sum"
}],
categoryAxis: {
type: "date",
baseUnit: getBaseUnit(period1, period2),
labels: {
rotation: -45,
dateFormats: {
days : getDateFormat(period1, period2),
weeks: getDateFormat(period1, period2),
years: getDateFormat(period1, period2)
},
step: getSteps(period1, period2)
},
majorGridLines: {
visible: false
}
},
valueAxis: {
majorGridLines: {
visible: true
},
labels: {
template: "#= kendo.format('{0}',value/1000)#K"
},
title: {
text: "Steps"
}
}
});
}
I also want to use the data from the above datasource for showing a summary of the information in a div below the chart. But if I add something like
var k = dSource.data;
there will not be any data in k. Is there a way to get the json data in the function which creates the chart?

DataSource.data is a function. I think your code should be:
var k = dSource.data();
That would also return an empty array if the data hasn't already been read, so you might need to do:
dSource.one("change", function () {
var k = dSource.data();
});
dSource.fetch();
because the .fetch() is async.

Related

Apexcharts remove old data series before render new series

I'm using apex chart for simple data visualization from json output. My charts based on pure javascript and not Vue or other frameworks.
My json (php) backend create two json outputs fro draw the chart as below
JSON 1
{
"x": "2019-05-27 16:18:48",
"y": "100"
},
{
"x": "2019-05-27 16:25:09",
"y": "110"
},
JSON 2
{
"x": "2019-05-27 16:18:48",
"y": "60"
},
{
"x": "2019-05-27 16:25:09",
"y": "65"
},
Based on the above two json outputs I retrieve data and draw my graph using the Category paired values method. below is the code responsible for retrieve data and draw the chart.
function for getting json data
function data_function(){
$.ajax({
type: "Get",
url: backend,
data:{
param: "all_a"
},
async: true,
cache: false,
success: function(data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data:{
param: "all_b"
},
async: true,
cache: false,
success: function(data) {
b_data = data;
chart(a_data,b_data);
}
});
}
});
}
function for draw chart
function draw_chart(a_data,b_data) {
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [
{
name: 'a',
data: a_data,
},
{
name: 'b',
data: b_data,
}],
yaxis: [
{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
},
]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
}
This works fine until I second time render the chart with new data. when I load the different data without reloading the windows chart happen to be laggy and render multiple times with the old incorrect data. sometimes I have to run the data_fnction multiple times to render the chart properly.
How can I fix this? Do I need to use function like appendchart ? how can I use wiht my data_function
You should call the render() method just once in the beginning (even with empty array it should work), then call the updateSeries() method in ajax call to update data of the chart.
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [],
yaxis: [{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
}]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
Your ajax call with updateSeries method of the chart
function data_function() {
$.ajax({
type: "Get",
url: backend,
data: {
param: "all_a"
},
async: true,
cache: false,
success: function (data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data: {
param: "all_b"
},
async: true,
cache: false,
success: function (data) {
b_data = data;
chart.updateSeries([{
name: 'a',
data: a_data
}, {
name: 'b',
data: b_data
}])
}
});
}
});
}
Docs for updateSeries
Although there is the updateSeries function, you're allowed to render again the values of the chart by destroying the previous ones. This works with ApexCharts, ChartJS, etc.
var options =
{
series: [],
chart:
{
type: 'donut',
height: 150
},
labels: ['...'],
};
// Destroy if exists in order to re-update the data
if (window.myChart)
window.myChart.destroy();
window.myChart = new ApexCharts(chart, options);
window.myChart.render();

telerik kendo chart bind to string

I am new to telerik kendo chart I have created a string that is being returned from an ashx page. I want the x Axis to be the date has in the month and year and for each date there will be two box going up to the number.
Is it the way I am sending the string back from the ashx page?
ASHX.CS Page
string JSON = sb.ToString();
context.Response.ContentType = "text/json";
context.Response.Write(JSON);
[
{
"Date":"2/2018"
"Images":"199956"
"ImagesDownloads":"540903"
},
{
"Date":"3/2018"
"Images":"226606"
"ImagesDownloads":"635068"
}
]
In my JS page
var DataSource = new kendo.data.DataSource({
transport: {
read: {
url: function() {
return "/URI";
},
dataType: "json"
}
},
group: {
field: "Date"
},
sort: {
field: "Date",
dir: "asc"
},
schema: {
model: {
fields: {
date: {
type: "date"
}
}
}
}
});
function createChart() {
$("#chart1").kendoChart({
dataSource: DataSource,
legend: {
position: "bottom"
},
series:
[{
field: "Images",
categoryField: "Date",
name: "Number of Images"
}, {
field: "ImagesDownloads",
categoryField: "Date",
name: "Number of Images download"
}],
categoryAxis: {
field: 'Date'
},
tooltip: {
visible: true,
shared: true
}
});
}
$(document).ready(function () {
$(document).ready(createChart);
$(document).bind("kendo:skinChange", createChart);
Please refer to this demo for grouped data bar chart.
This demo also shows you how Kendo supports date formatting on category axis you may use the API Reference for more information.

How to bind dynamic data to highcharts basic area graph

I have to create the following graph and i have to dynamically load data into it.
Basic Area http://domoticx.com/wp-content/uploads/highcharts-area-basic-standaard.png
Could anyone please help me understanding how can it be done.
Below is where i am able to reach.:
$.ajax({
url: 'EthicsData',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: false,
processData: false,
cache: false,
delay: 150,
success: function (data) {
var EthicReg = (data[0].regdet);
var EthicComp = (data[0].compdet);
var EthicsCompletions = new Array();
var EthicsRegistration = new Array();
for (var i in EthicReg) {
var serie = new Array(EthicReg[i].Value, EthicReg[i].year);
EthicsRegistration.push(serie);
}
for (var y in EthicComp) {
var series2 = new Array(EthicComp[y].value,
EthicComp[y].year);
EthicsCompletions.push(series2);
}
DrawEthicsAndCompl(EthicsCompletions, EthicsRegistration)
},
error: function (xhr) {
alert('error');
}
});
};
function DrawEthicsAndCompl(EthicsCompletions, EthicsRegistration) {
debugger;
var chart = new Highcharts.Chart({
chart: {
//plotBackgroundColor: null,
//plotBorderWidth: 1, //null,
//plotShadow: false,
renderTo: 'container1',
type: 'area'
},
title: {
text: 'US and USSR nuclear stockpiles'
},
subtitle: {
text: 'something'
},
xAxis: {
allowDecimals: false,
labels: {
formatter: function () {
return 10; // clean, unformatted number for year
}
}
},
yAxis: {
title: {
text: 'Nuclear weapon states'
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name} produced <b>{point.y:,.0f}</b><br/>warheads in {point.x}'
},
plotOptions: {
area: {
pointStart: 2010,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: [{
name: 'Registration',
data: [EthicsRegistration[0]]
}, {
name: 'Completions',
data: [EthicsCompletions[0]]
}]
});
}
Here is the link which demo's same but static data:
(http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/area-basic/)
Just change the order in which you are pushing items in array , means
Instead
var serie = new Array(EthicReg[i].Value, EthicReg[i].year);
EthicsRegistration.push(serie);
Use
var serie = new Array(EthicReg[i].year, EthicReg[i].Value);
EthicsRegistration.push(serie);
Also , If you are getting year's value don't use pointStart: 2010 instead leave it on the data you are getting from the response above.
Thanks #Nishith for providing the right direction. I modified the code as below:
name: 'Registration',
data: [EthicsRegistration[0][1], EthicsRegistration[1][1], EthicsRegistration[2][1]]
}, {
name: 'Completions',
data: [EthicsCompletions[0][1],EthicsCompletions[1][1],EthicsCompletions[2][1]]
}]
});

KnockoutJS components with KendoUI chart only works for the last chart

I have an Observable Array of items that creates components with a parameter.
Within each component, I use that parameter to query for data (through AJAX). I return that data into an Observable Array and use that Array as a data source for a KendoUI chart.
Example of list of created components with a parameter:
<csglist params="account:'08167526'"></csglist>
<hr>
<csglist params="account:'0873458'"></csglist>
<hr>
<csglist params="account:'0828337'"></csglist>
<hr>
<csglist params="account:'086778'"></csglist>
call that gets the data
getCategory = function () {
self.categoryChart([]);
xhr_get(cont.publish + 'api/dbmain/getCategory', { 'id': params.account }).done(function (allData) {
var mappedLogs = $.map(allData, function (item) { return new categoryData(item) });
self.categoryChart(mappedLogs);
buildChart();
})
}
function buildchart(){
$(document).ready(createChart);
$(document).bind("kendo:skinChange", createChart);
}
the create chart
function createChart() {
$("#" + self.act() + "chart").kendoChart({
dataSource: {
data: ko.toJS(self.categoryChart)
//, sort: { field: "category", dir: "asc" }
},
title: {
text: self.type()
},
legend: {
visible: true,
position: "bottom"
},
seriesDefaults: {
type: "bar",
stack: true
},
series: [{
field: "sales",
name: "Current Sales",
color: "#66110F"
}, {
field: "opp",
name: "Opportunity",
color: "#E65F5B"
}],
valueAxis: {
// max: 180,
line: {
visible: false
},
minorGridLines: {
visible: true
},
visible: false
},
categoryAxis: {
field: "category",
majorGridLines: {
visible: false
}
},
tooltip: {
visible: false,
template: "#= series.name #: #= value #"
}
});
}
But when the components are all created, only the last one has data.
Can anyone tell me why is this happening?
when I changed the the buildChart = function to self.buildChart = function, it works!

Getting a string on an update request in KendoUI datasource

I have a pretty simple grid with data source that retrieves data correctly
For that cause I have a schema.parse function defined
The problem is that when I try to update/create new row the schema.parse() called again and the parameter that is passed to it is a string that contains the HTML of my page. cannot really get what the hell is going on there.
thanks
var _dataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: layerDefProvider.getLayerUrlById("surveys") + "/query",
data: {
f: "json",
//token: token,
outFields: "*",
//outSR: 3857,
where: "1=1"
},
type: "POST"
},
create: function (options) {
console.debug("called");//never gets called
},
update: function (options) {
console.debug("called");//never gets called
},
destroy: function (options) {
console.debug("called");//never gets called
}
},
filter: {
field: "OBJECTID", operator: "eq", value: 0
},
schema: {
data:function(response) {
},
parse: function (data) {//on loading it is fine, on updating the data param is a string of my HTML of the page
var rows = [];
var features = data.features;
if (!features) {
return [];
}
for (var i = 0; i < features.length; i++) {
var dataRow = {};
dataRow.OBJECTID = features[i].attributes.OBJECTID;
dataRow.Name = features[i].attributes.Name;
dataRow.Date = features[i].attributes.Date;
dataRow.Comment = features[i].attributes.Comment;
rows.push(dataRow);
}
return rows;
},
model: {
id: "OBJECTID",
fields: {
OBJECTID: { type: "number", editable: false },
Name: { type: "string" },
Date: { type: "string" },
Comment: { type: "string" }
}
}
}
});
var _surveysPicker = $(config.table).kendoGrid({
toolbar: ["create","save"],
editable: true,
dataSource: _dataSource,
height: 300,
sortable: true,
selectable: "multiple",
columnMenu: true,
resizable: true,
columns: [{
field: "OBJECTID",
width: 40
}, {
field: "Name",
width: 40
}, {
field: "Date",
width: 40
}, {
field: "Comment",
width: 100
}]
});
You need to move your parse function inside read event if you need to parse data only on read action.

Categories

Resources