How to bind data to line chart in highcharts in MVC3? - asp.net-mvc-3

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);

Related

kendo chart refresh data not change

I'm using a Kendo Chart, the first call works fine but when I call refresh_interval 5000 is called, the charts doesn't update. he updated data is displayed on the console.
brings back the old results every time. When I refresh the page, I want the chart to bring the updated results.
What am i doing wrong?
my code :
<script th:inline="javascript">
$(function(){
var page = 1;
createMonthChart(today, 1);
$(window).resize(function(){
$("#chart_month").data("kendoChart").refresh();
});
});
function createMonthChart(today, page) {
var date = today;
$("#chart_month").kendoChart({
dataSource: {
transport: {
read: {
url: "dashboard/monthProcess.json?date="+date+"&&pageNo="+page
}
}
},
legend: {
position: "bottom",
labels: {
margin:5,
},
},
seriesDefaults: {
type: "column",
stack: true,
labels:{
visible :true,
position:"center",
background : "transparent",
template: "#if (value > 0) {# #: value # #}#"
}
},
series: [{
field: "success",
name : "success",
categoryField: "processName"
},
{
field: "fail",
name : "fail",
categoryField: "processName"
}
],
seriesColors: ["#3CB371", "#FF6347"],
});
}
</script>
<script th:inline="javascript">
var refresh_interval = 5000;
$(function(){
var timer;
var select = $("select#resetTimeSelect");
select.siblings("label").text(select.children("option:selected").text()); //refresh time select
select.change(function(){
var select_name = $(this).children("option:selected").text();
$(this).siblings("label").text(select_name);
window.refresh_interval = $(this).children("option:selected").val();
refresh();
});
window.onbeforeunload = function() {
clearInterval(window.timer);
}
var ajaxRunning = false;
refresh();
});
function refresh(){
if(window.refresh_interval != "stop"){
window.timer = setInterval(function(){
loadRobotCount();
pageNo = pageNo + 1;
if(pageNo == totalPage){
pageNo = 1;
}
ChartRefreshMonth(today, pageNo);
}, window.refresh_interval);
}
}
function ChartRefreshMonth(today, page){
var date = today;
$.ajax({
url: "dashboard/monthProcess.json?date="+date+"&&pageNo="+page,
type : "GET",
dataType : "json",
cache : false,
contentType : "text/json; charset=UTF-8",
success : function(data) {
totalPage = data[0].recordCountPerPage;
$("#chart_month").data("kendoChart").dataSource.read();
var chart = $("#chart_month").data("kendoChart");
chart.refresh();
},
error : function(xhr, status, err){
alert(FailMessage);
}
});
}
</script>
In ChartRefreshMonth, this code:
$("#chart_month").data("kendoChart").dataSource.read();
does a call to the backend with the old url.
The result of the call that you are making isn't passed anywhere.
You need to pick 1 of 2 approaches:
the dataSource handles the back-end calls
you handle the calls and then do dataSource.data(result)
Both will work, but you need to pick one and do it right.

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();
});

Highcharts multiple series from json

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);
}
});
});

How to show the json data in Pie chart HighChart?

HI all i have a json data which looks like this
[ "Data":[
{"Id":"1 ","EmployeeName":Anil},
]
which i am geting from my controller action
public ActionResult Index()
{
var data = GetData();
return View();
}
public JsonResult GetData()
{
int Param1;
Param1 = 1;
var EmployeeDetails = db.EmployeeDetails.ToList<EmployeeDetail>().Select(e =>
new
{
id=e.EmployeId,
Name = e.EmployeeName
});
return Json(EmployeeDetails , JsonRequestBehavior.AllowGet);
}
now i want this json data to a pie chart..how can i do this
Here instead of calling your jsonresult method in action method do it using $.getJSON method
public ActionResult Index()
{
return View();
}
public JsonResult GetData()
{
int Param1;
Param1 = 1;
var EmployeeDetails = db.EmployeeDetails.ToList<EmployeeDetail>().Select(e =>
new
{
id=e.EmployeId,
Name = e.EmployeeName
});
return Json(EmployeeDetails , JsonRequestBehavior.AllowGet);
}
here u can call your method like this and bind it to your chart
<script type="text/javascript">
$(function () {
$.getJSON('<%= Url.Action("YourMethod","YourControllerName") %>', {}, function (data) {
var json = data;
var jsondata = [];
for (var i in json) {
// var serie = new Array(json[i].Projects, json[i].Bugs);
jsondata.push([json[i].EmployeId, json[i].EmployeeName]);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Resource Reports of BugTracker'
},
plotOptions: {
pie: {
showInLegend: true,
animation: false,
allowPointSelect: true,
cursor: 'pointer'
}
},
legend: {
enabled: true
},
series: [{
type: 'pie',
data: jsondata
}]
});
});
});
</script>
Regardless of what type of data you have, creating a pie chart is fairly straightforward. See a working example here: http://livecoding.io/3437833
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
plotOptions: {
pie: {
animation: false,
allowPointSelect: true,
cursor: 'pointer'
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});

Resources