Highcharts multiple series from json - ajax

My JSON looks like:
[[[773,1363709520],[774,1363709580]],[[1546,1363709520],[1548,1363709580]]]
I would like highcharts to create a new series every time it reaches a new JSON array: [[1546,1363709520],[1548,1363709580]]
I have a hard coded version, but making my data[[]] is not helping...
$(function () {
var data = [];
var data1 = [];
$.ajax({
url: "http://localhost:8080/vdm-stats-core/stats/metrics?from=2&src=org.example.fib&customer=customer0&server=server0&metric=responses.count",
dataType: "jsonp", // Notice! JSONP <-- P (lowercase)
jsonp: "callback",
success: function (inData) {
console.log(inData[0][1][0]);
var xval = new Date();
for (a = 0; a < inData.length; a++) {
for (i = 0; i < inData[a].length; i++) {
var yval = inData[a][i][0];
xval = inData[a][i][1];
var x = [xval, yval];
if (a == 0) {
data.push(x);
}
if (a > 0) {
data1.push(x);
}
}
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
title: {
text: 'Test',
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Customer0',
data: data
}, {
name: 'Customer1',
data: data1
}]
});
},
error: function () {
console.log(arguments);
}
});
});
Please help!

I tried to understand your code, here's my intepretation;
function success(inData) {
var customerNr,
timestamp,
VALUE = 0,
TIMESTAMP = 1,
series = {},
len = inData.length,
yval,
item;
for (customerNr = 0; customerNr < len; customerNr++) {
// Init series object literal for customer
series[customerNr] = {
name : 'Customer '+customerNr.toString(),
data : []
};
// Setup data for customer
for (item = 0; item < inData[customerNr].length; item++) {
yval = inData[customerNr][item][VALUE];
timestamp = inData[customerNr][item][TIMESTAMP];
series[customerNr].data.push([timestamp,yval]);
}
// Add series, but redraw only on last customer
chart.addSeries(series[customerNr],customerNr===len-1);
}
};
You recycle the series object for each customer, but I've added a customerNr property. addSeries method in Highchart will by default redraw chart (http://api.highcharts.com/highcharts#Chart.addSeries()). I've selected to only redraw chart on last customer. Forked fiddle example at; http://jsfiddle.net/hkskoglund/VVLNV/

The important thing to keep in mind is that the series object is already a json object...
So the easiest thing to do, assuming you control the creation of the json file, is format the json output as the entire series object:
[{ name: 'Customer0', data: [[773,1363709520],[774,1363709580]] }, { name: 'Customer1', data: [[1546,1363709520],[1548,1363709580]] }]
and then:
series: myData

I got it to work:
Had to reset my series data.
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
title: {
text: 'Test',
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime'
},
series: []
});
$.ajax({
url: "http://localhost:8080/vdm-stats-core/stats/metrics?from=200&src=org.example.fib&customer=customer0&server=server0&metric=responses.count",
dataType: "jsonp", // Notice! JSONP <-- P (lowercase)
jsonp: "callback",
success: function (inData) {
var xval = new Date();
var series = {
name: 'Customer',
data: []
}
for (a = 0; a < inData.length; a++) {
for (i = 0; i < inData[a].length; i++) {
var yval = inData[a][i][0];
xval = inData[a][i][1];
var x = [xval, yval];
series.data.push(x);
}
chart.addSeries(series);
series.data = [];
}
},
error: function () {
console.log(arguments);
}
});
});

Related

How to use values from an ajax request in google charts?

I am creating an array of objects using Ajax to use as values in a google line chart, however the values do not render even though I can view them through the console.
I have tried using ajax complete function to call the charts once the values are set but it still doesn't work, I suspect it's due to scoping but I don't know how to resolve it. here is my code
complete array
studentCount[
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
}
{
month:5,
count:4
}
etc...
]
code
$.ajax({
dataType: "json",
url: url,
success: function (data) {
for (var i = 0; i < data.length; i++) {
studentCount[data[i].month -1].count = data[i].count;
}
}
});
$( document ).ajaxComplete(function() {
google.charts.load('current', {
packages: ['line']
});
google.charts.setOnLoadCallback(drawLineColors);
console.log(JSON.stringify(studentCount[0].count)) //returns correct value
function drawLineColors() {
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count],
['June', studentCount[5].count],
['July', studentCount[6].count],
['August', studentCount[7].count],
['Septembre', studentCount[8].count],
['October', studentCount[9].count],
['November', studentCount[10].count],
['December', studentCount[11].count]
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
recommend loading google first, you can include the callback directly in the load statement
once loaded, then call ajax
see following working snippet, adjust as needed to get proper data,
and change error to success as the url isn't reachable from here...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437']
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
});
},
packages: ['line']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
also, recommend using core chart instead of material,
several config options simply don't work with material charts
core chart, use package --> corechart
and chart --> google.visualization.LineChart
you can use config option theme: 'material' to get the core chart close to the look and feel of a material chart
see following working snippet...
google.charts.load('current', {
callback: function () {
var url = 'some url';
$.ajax({
dataType: 'json',
url: url,
error: function (data) { // <-- change 'error' to 'success' to run locally
//for (var i = 0; i < data.length; i++) {
//studentCount[data[i].month - 1].count = data[i].count;
//}
var studentCount = [
{
month:1,
count:5
},
{
month:2,
count:3
},
{
month:3,
count:9
},
{
month:4,
count:0
},
{
month:5,
count:4
}
];
var data = google.visualization.arrayToDataTable([
['Month', '2015'],
['January', studentCount[0].count],
['Febuary', studentCount[1].count],
['March', studentCount[2].count],
['April', studentCount[3].count],
['May', studentCount[4].count]
// etc...
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Number of Students'
},
colors: ['#4285f4', '#db4437'],
theme: 'material'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Simile Timeline - Events present but not displaying

I am working on a site that uses the Simile Timeline. I am using Kendo Core for the single page application components. I am loading the timeline from the results of an ajax request. I am manually adding the events. When I check the console the events are populated on the event source. However events do not display.
What do I need to change to get the events to display on the timeline?
Thanks in advance.
///////////////////////////////
// Timeline
///////////////////////////////
var timelineViewModel = kendo.observable({
InitUI: function (id) {
var self = this;
$.ajax({
url: "api/timelines/" + id,
type: "GET",
dataType: "json",
contentType: "application/json",
success: function (data) {
self.loadTimeLine(data);
}
});
},
loadTimeLine: function (data) {
SimileAjax.History.enabled = false;
$('#TimelineTitle').text(data.title);
var tl_el = document.getElementById("my-timeline");
var eventSource1 = new Timeline.DefaultEventSource();
for(var eIndex = 0; eIndex < data.events.length; eIndex ++)
{
var evt = new Timeline.DefaultEventSource.Event({
title: data.events[eIndex].title,
start: data.events[eIndex].start,
description: data.events[eIndex].description,
caption: data.events[eIndex].title,
color: '#FFCC33',
text: data.events[eIndex].title
});
eventSource1._events.add(evt);
}
var theme1 = Timeline.ClassicTheme.create();
theme1.event.bubble.width = 320;
theme1.event.bubble.height = 220;
var d = data.MinDate;
var bandInfos = [
Timeline.createBandInfo({
width: 100, // set to a minimum, autoWidth will then adjust
intervalUnit: Timeline.DateTime.YEAR,
intervalPixels: 200,
eventSource: eventSource1,
date: d,
theme: theme1,
layout: 'overview'
}),
Timeline.createBandInfo({
width: 100, // set to a minimum, autoWidth will then adjust
intervalUnit: Timeline.DateTime.MONTH,
intervalPixels: 200,
eventSource: eventSource1,
date: d,
theme: theme1,
layout: 'overview'
}),
Timeline.createBandInfo({
width: 350, // set to a minimum, autoWidth will then adjust
intervalUnit: Timeline.DateTime.WEEK,
intervalPixels: 200,
eventSource: eventSource1,
date: d,
theme: theme1,
layout: 'original'
})
];
bandInfos[1].syncWith = 2;
bandInfos[1].highlight = true;
bandInfos[0].syncWith = 2;
bandInfos[0].highlight = true;
tl = Timeline.create(tl_el, bandInfos, Timeline.VERTICAL);
tl.layout();
}
})
var timelineView = new kendo.View(
"timelineTemplate",
{
model: timelineViewModel
}
);
///////////////////////////////
// Layout
///////////////////////////////
var layout = new kendo.Layout("<div id='content'></div>");
///////////////////////////////
// DAS ROUTER
///////////////////////////////
var router = new kendo.Router();
router.route("(:viewName)/(:id)", function (viewName, id) {
layout.render("#maincontent");
if (viewName) {
switch (viewName.toLowerCase()) {
case "timeline":
if (id) {
if (id.toLowerCase() == "new") {
layout.showIn("#content", createTimelineView);
createTimelineViewModel.InitUI();
}
else {
layout.showIn("#content", timelineView);
timelineViewModel.InitUI(id);
}
}
break;
case "account":
if (id) {
layout.showIn("#content", accountView);
accountViewModel.InitUI(id);
}
break;
}
}
else {
layout.showIn("#content", indexView);
indexViewModel.InitUI();
}
});
$(function () {
router.start();
});

HighChart Pie Dynamic JSON in Codeigniter

Any help for this? The problem is I cannot get the data in pie. Any ideas? I tried to echo it outside the pie graph view, and the data appears in JSON as [{"Terminal":"13"}]. The Hightchart needs the data as ["Sample", 2]? Any suggestion sir on how to convert it like that? Thanks.
Heres my code:
VIEW
$(document).ready(function () {
$(function () {
var chart;
// Build the chart
$('.widget-lower-left#widget').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Availability'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Availability',
data: []
}]
});
});
function requestData() {
$.ajax({
url: 'home',
datatype: "json",
success: function(data) {
alert(data);
console.log(data);
chart.series[0].setData(data);
},
cache: false
});
};
});
then in the MODEL
$results = $this->db->query("SELECT COUNT(get_jeeps_availability) as Terminal FROM get_jeeps WHERE get_jeeps_availability = 'Terminal'");
return $results->result_array();
in the CONTROLLER
public function index()
{
$data['pie'] = json_encode($this->get_model->dashboard_jeep_widget());
$this->load->view('home',$data);
}
In requestData() function, before setting data, preprocess 'data' that way:
var newData = [];
for( var i = 0, len = data.length; i < len; i++ ) {
var item = data[i];
for(var j in item){
newData.push([j,item[j]]);
}
}
chart.series[0].setData(newData);

How to bind data to line chart in highcharts in MVC3?

Hi all i have storedprocedure which where i get the output data like this
var loggedbugs
projectName ProjectYear ProjectMonth Week1 Week2 Week3 Week4 Week5
Ecommerce 2012 8 0 1 4 3 0
var loggedbugs
projectName ProjectYear ProjectMonth Week1 Week2 Week3 Week4 Week5
Ecommerce 2012 8 2 2 8 3 0
and i call this storedprocedure in my MVC application and return this data as Json like this
public ActionResult Index()
{
return View();
}
public JsonResult CreatedBugs()
{
int year;
int month;
int projectid;
year = 2012;
month = 8;
projectid = 16;
var loggedbugs = db.ExecuteStoreQuery<LoggedBugs>("LoggedBugs #Year,#Month,#ProjectID", new SqlParameter("#Year", year), new SqlParameter("#Month", month), new SqlParameter("#ProjectID", projectid)).ToList();
var ClosedBugs = db.ExecuteStoreQuery<LoggedBugs>("ClosedBugs #Year,#Month,#ProjectID", new SqlParameter("#Year", year), new SqlParameter("#Month", month), new SqlParameter("#ProjectID", projectid)).ToList();
var model = new LoggedBugs
{
LoggedBugsCount = loggedbugs,
ClosedBugs = ClosedBugs
};
return Json(model, JsonRequestBehavior.AllowGet);
}
model return me record count two here...so now what i want to do is ...this data should be binded to linechart where LoggedBugsCount should have a different line and ClosedBugs should have a different line...
and weeks should be on Xaxis and y axis should have the count....
can any one help me here in how to bind this data line chart in highcharts..this is what i am trying for now but there is no result
<script type="text/javascript">
$(document).ready(function () {
alert(1);
$.getJSON('<%= Url.Action("CreatedBugs","WeeklyLoggedBugs") %>', {}, function (data) {
var json = data;
alert(data);
var loggedbugs = [];
var closedbugs = [];
for (var i in json) {
// var serie = new Array(json[i].Projects, json[i].Bugs);
//jsondata.push([json[i].projectName, json[i].ProjectYear, json[i].ProjectMonth, json[i].Week1, json[i].Week2, json[i].Week3, json[i].Week4, json[i].Week5]);
loggedbugs.push([json[i].LoggedBugsCount]);
closedbugs.push([json[i].ClosedBugs]);
}
chart.series[0].data = loggedbugs;
chart.series[1].data = closedbugs;
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Daily Reports'
},
subtitle: {
text: 'Logged Bugs'
},
xAxis: {
categories: ['Week1', 'Week2', 'Week3', 'Week4', 'Week5']
},
yAxis: {
title: {
text: 'Temperature (°C)'
}
},
tooltip: {
enabled: false,
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '°C';
}
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'line',
name: 'Logged Bugs'
},
{
type: 'line',
name: 'ClosedBugs'
}]
});
});
});
</script>
See here
chart.series[0].data = loggedbugs;
chart.series[1].data = closedbugs;
var chart;
chart = new Highcharts.Chart({
........
});
First, You are adding data to series before creating Chart and even defining chart variable.
Second, You can set data in series using:
series: [{
name: 'Logged Bugs',
data: loggedbugs
},
{
name: 'ClosedBugs',
data: closedbugs
}]
So, You event don't need
chart.series[0].data = loggedbugs;
chart.series[1].data = closedbugs;
Here is the example: http://jsfiddle.net/mhardik/JRq7Z/
EDIT:
I dont know asp.net MVC3
Check whether you are getting data. Print response in console using console.log() if you are using FF.
for (var i in json) {
loggedbugs.push([json[i].LoggedBugsCount]);
closedbugs.push([json[i].ClosedBugs]);
}
// Check
console.log(loggedbugs); console.log(closedbugs);

JSON Data Map Issue with HighCharts + Ajax

I have the follow data returned via JSON
{"rows":[{"Date":"07/10/2011","Value":1206,"Action":"Drink"},
{"Date":"07/11/2011","Value":2288,"Action":"Pie"},
{"Date":"07/12/2011","Value":1070,"Action":"Drink"},
{"Date":"07/13/2011","Value":1535,"Action":"Beer"},
{"Date":"07/14/2011","Value":1721,"Action":"Drink"}],
"page":1,"total":1,"records":5}
I am trying to use this data with HighCharts but getting a bit confused.
jQuery.ajax({
url: fullPath + 'datamap',
dataType: "json",
type: 'POST',
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
});
// Create the chart
var chart = new Highcharts.Chart(options);
},
cache: false
});
I am trying to chart "Date" and "Value" ?
As I understand you need to show rows values with Highcharts. So firstly your initial data will be:
var chartData = data.rows;
Now chartData is just an array of objects. Use for loop to iterate through chartData like below:
var seriesData = [];
for (var i = 0; i < chartData.length; i++)
{
var x = new Date(chartData[i].Date).getTime();
var y = chartData[i].Value;
seriesData.push([x, y]);
}
After this loop you will have seriesData array of points that can be used in Highcharts. Now just render it:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartContainer',
defaultSeriesType: 'line'
},
xAxis: {
type: 'datetime'
},
series: [{
data: seriesData
}]
});
Voila!
Test this: http://jsfiddle.net/ebuTs/8263/

Resources