I am trying to populate highchart from server side using json object.frankly speaking I have average knowledge of jquery and highchart. I am newbie in json, jquery and highchart.
I am able to receive the json object from server side but facing issue while populating highchart.
can any body help me with this.
my json object receive from server look like this
[Object { year=2001, populations=10000}, Object { year=2002, populations=20000}, Object { year=2003, populations=30000}, Object { year=2004, populations=40000}, Object { year=2005, populations=50000}, Object { year=2006, populations=60000}, Object { year=2007, populations=70000}]
my script to populate the highchart is
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'dispatcherServlet/reportController/getreport',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
var name = Array();
var value = Array();
var dataArrayFinal = Array();
for (i = 0; i < data.length; i++) {
name[i] = data[i].year;
value[i] = data[i].populations;
}
for (var j = 0; j < name.length; j++) {
var temp = new Array(name[j], value[j]);
dataArrayFinal[j] = temp;
}
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "City Population"
},
xAxis: {
allowDecimals: false,
title: {
text: "Year"
}
},
yAxis: {
title: {
text: "Population",
data: value[i].year
}
},
series: [{
data: dataArrayFinal
}]
});
}
});
});
When I am simply passing my data receive from server to highchart series. I am getting balnk highchart.
The second script look like this
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/dispatcherServlet/reportController/getreport',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
// alert(data[i].year);
// alert(data[i].populations);
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "City Population"
},
xAxis: {
allowDecimals: false,
title: {
text: "Year"
}
},
yAxis: {
title: {
text: "Population",
}
},
series: [{
data: data
}]
});
}
}
});
});
Finally it worked
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/dispatcherServlet/reportController/getreport',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
// Populate series
var processed_json = new Array();
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].year, parseInt(data[i].populations)]);
}
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "City Population"
},
xAxis: {
allowDecimals: false,
title: {
text: "Year"
}
},
yAxis: {
title: {
text: "Population"
}
},
series: [{
data: processed_json
}]
});
}
});
});
[ { "year":2001, "populations":10000},
{ "year":2002,"populations":20000},
{ "year":2003, "populations":30000},
{ "year":2004, "populations":40000},
{ "year":2005, "populations":50000},
{ "year":2006, "populations":60000},
{ "year":2007, "populations":70000}
]
var title = prompt("Please enter Title of your Chart: ", "");
// var chart = $('#container').highcharts();
var x=new Array();
//var product = prompt("Please enter Column Name: ", "");
var stock = prompt("Please enter Y Axis Name: ", "");
//var name = prompt("Please enter Series Name: ", "");
$(function () {
var text="Stock Level";
var y=new Array();
var attr="";
var processed_json = new Array();
$.getJSON('data2.json', function(data) { //Getting data from JSON file
//var keys=new Array();
var obj=JSON.stringify(data[1]);
//alert(obj);
attr=JSON.stringify(obj.substring(2,obj.indexOf(":")-1))
//alert(JSON.stringify(obj.substring(2,obj.indexOf(":")-1)));
var attr1=attr.substring(1,attr.length-1);
//alert(attr1);
//alert(attr1);
$.each(data, function(key, value)
{
// var yName="Stock";
//var product="ProductId";
var idd=value[attr1];
//Getting Values of 1st Attribute that has to be represented along X-axis
x.push(idd);
//Getting Values of 2nd attribute that has to be represented along Y-axis
y.push(value.populations);
//$("ul").append("<li>"+value.ProductId+" "+value.Stocklevel+"<li>")
});
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: title
},
xAxis: {
categories: x, //Populating X-axis
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: stock
}
},
series: [
{
name: name ,
data:y //Populating Y-axis
}
]
});
});
});
Related
I have a Kendo grid which is rendered as soon as the page loads. The grid is populated by remote data.
logMonitoringGrid.kendoGrid({
dataSource: {
batch: true,
transport: {
read: {
url: window.$vars['webApiHost'] + "logs",
dataType: "json",
}
},
serverFiltering: false,
serverPaging: false,
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number" },
TTId: { type: "string" },
LUId: { type: "number" },
Level: { type: "string" },
Server: { type: "string" },
Thread: { type: "number" },
Message: { type: "string" },
Ip: { type: "string" },
RId: { type: "string" },
Timestamp: { type: "date" }
}
}
}
},
columns: columnObjects
});
var lGrid = logMonitoringGrid.data("kendoGrid");
There's another API which has the data of all the tenants like this (JSON)
{
Id: 5196
Name: "unittest"
ContactEmail: "admin#unittest.com"
Theme: "default"
DefaultLocale: "en-US"
IsInternal: false
}
I need to replace the Tenant Id of each row of the grid with their corresponding tenant names. The remote data of the grid does not send any tenant names with it. That's why I am creating a map of all the tenant ids and their names.
var tenantData = new kendo.data.DataSource({
transport: {
read: {
beforeSend: function (xhr) {
o9Util.setRequestHeaders(xhr);
},
url: crudUrl("tenants"),
dataType: "json"
}
}
});
var myMap = new Map();
tenantData.fetch(function () {
var data = tenantData.data();
for (var i = 0; i < data.length; i++) {
myMap.set(data[i].Id, data[i].Name);
}
})
Now I'm updating the grid column like this
lGrid.dataSource.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
for (var [key, value] of myMap.entries()) {
if (parseInt(data[i].TTId) === key) {
data[i].set("TTId", value);
}
}
}
})
This approach works but takes some time to change the values of the column whenever the page loads. Moreover the page becomes unresponsive after some time. Is there any other way I can update the grid as soon as the page loads?
A suggest the following:
Make your API(tenants) call before Kendo's call. Remember to initialize the grid when this requests finishes, that means, on DataSource's requestEnd event;
Initialize your grid;
In the Grid's dataSource.schema.parse you set the values you want. Example:
logMonitoringGrid.kendoGrid({
dataSource: {
schema: {
parse: function(data) {
let tenantJsonData = tenantData.data().toJSON();
data.forEach(item => {
let tenantItem = tenantJsonData.find(ti => ti.Id === item.TTId);
if (tenantItem) {
item.TTTId = tenantItem.Name;
}
});
return data;
}
}
}
}
I didn't tested it, but it should work.
I am trying to populate a C3 chart with dynamic data from a SQL database. I have c# web method that when called by my javascript produces the following JSON string
[{"y":"5","item1":"Lion Wharf"},{"y":"31","item1":"Millbrook Park P2"},{"y":"84","item1":"Pinfield Meadows"}]
I'm using the following javascript on pageload but getting error "a.forEach is not a function"
$.ajax({
type: "POST",
url: "additions.aspx/GetPiechartData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (result) {
OnSuccess(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
function OnSuccess(response) {
var abc = JSON.stringify(response);
window.location.replace(response);
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: response,
keys: {
x: 'y',
value: ['item1']
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
});
I'm very new to Javascript and would really appreciate a pointer here
Thanks!
You have to format your json response to fit the expected format of C3 for Donut graph type.
function OnSuccess(response) {
var data = {};
var value = [];
JSON.parse(response).forEach(function(d) {
data[d.item1] = d.y;
value.push(d.item1);
});
c3.generate({
data: {
json: [data],
keys: {
value : value
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
})
}
Your server will normally output a string, so using a JSON.parse will transform this string into a json object.
function OnSuccess(response) {
var jsonData = response.d;
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: JSON.parse(jsonData),
}
});
}
i'm trying to display data from database into a linear highchart. this is the json response from my controller which is retrieved from database:
[{"protocole":"tcp","date":"01/02/20","time":"00:10:20","total":281},
{"protocole":"udp","date":"01/02/20","time":"00:10:30","total":201},
{"protocole":"tcp","date":"01/02/20","time":"00:10:40","total":100}}
i succeeded to display data in the yAxix from data base but i've tested it with static data in the xAxix this is the code :
$(document).ready(function() {
var options={
chart: {
renderTo: 'container',
type: 'line'
},
title : {
text: 'Total Request number'
},
subtitle : {
text: 'Server num1'
},
xAxis : {
categories: ['00:10:20','00:10:30','00:10:40']
},
yAxis :{
title: {
text: 'Total'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip : {
valueSuffix: '\xB0C'
},
legend : {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series : [{}]
}
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
$.each(data, function(i) {
array.push(data[i].total);
})
alert(array);
options.series[0]= {"name": 'total',
"data":array};
var chart = new Highcharts.Chart(options);
}
});
});
now i want the categories to be dynamic and retrieve time and put it on axis .
I have tried this code but still not working !
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
var array1=[];
$.each(data, function(i) {
array.push(data[i].total);
array1.push(data[i].time);
})
// alert(array);
options.series[0]= {"name": 'total',
"data":array};
options.xAxis.categories=array1;
var chart = new Highcharts.Chart(options);
}
});
do somebody have an idea how to do this ?
thanks in advance .
I've tested this code and it works perfectly !
I don't know why this didn't work for the first time and showed errors and now works !
I post it maybe it could help someOne. if someone knows why it will be better to mention it .
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
var array1=[];
$.each(data, function(i) {
array.push(data[i].total);
array1.push(data[i].time);
})
// alert(array);
options.series[0]= {"name": 'total',
"data":array};
options.xAxis.categories=array1;
var chart = new Highcharts.Chart(options);
}
});
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]]
}]
});
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.