not able to display data in google charts using json - javascript

I am getting the data from MySQL and want to display it in a line chart using google charts. I am using java and javascript.
this is the type of data which i am getting from MySQL:
timestamp 2017-06-12 19:22:23.0 , 2017-06-12 19:22:25.0
f1 414 413
I got this data in a resultset and converted it into JSONarray and the output is like:
'[{"f1":414,"ts":"2017-06-12 19:22:23.0"},{"f1":415,"ts":"2017-06-12 19:22:25.0"}]'
-> from a servlet i am passing this string to a jsp file.
Now the JSP file:
<script type="text/javascript">
$(document).ready(function(){
alert('hello');
});
var newstring = <%= request.getAttribute("json_string")%>
<%System.out.println(request.getAttribute("json_string"));%>
var chartData = JSON.parse(newstring);
// Load google charts
google.load('visualization', '1.1', {packages:["corechart, table"]});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
var dTable = new google.visualization.DataTable();
dTable.addColumn('string','timestamp');
dTable.addColumn('number','f1');
for(i=0;i<chartData.length;i++)
{
var currentObj = chartData[i];
dTable.addRow([currentObj.f1,currentObj.ts]);
}
// Display the chart inside the <div> element with id="linechart"
var options = {'title':'<%= request.getAttribute("Spring_type") + " for date :"%><%= request.getAttribute("date")%>', 'width':550, 'height':400};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(data, options);
</script>
The chart is not getting displayed.
Any help would be appreciated. Or if there is any other way please write it down.

You are adding all your values to dTable while your are using some variable data while creating the chart, the correct way should be
chart.draw(dTable , options);
and there is no drawChart function , you should wrap everything in the function lioke
function drawChart(){
var dTable = new google.visualization.DataTable();
dTable.addColumn('string','timestamp');
dTable.addColumn('number','f1');
for(i=0;i<chartData.length;i++)
{
var currentObj = chartData[i];
dTable.addRow([currentObj.f1,currentObj.ts]);
}
// Display the chart inside the <div> element with id="linechart"
var options = {'title':'<%= request.getAttribute("Spring_type") + " for date :"%><%= request.getAttribute("date")%>', 'width':550, 'height':400};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(dTable , options);
}
Also look at this example from the api docs

Related

Locale language for google charts not working

In my page I load the chart as described in the docs. It's a view in asp.net that renders the output. The view checks if a class called Avstemning is populated then puts strings from that class into the chart as data. But if I use Norwegian letters like ø,æ, å. The chart data can't read it even as I specify the language option to use. What is going on here?
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
#if (Model.Avstemning != null)
{
<script type="text/javascript">
google.charts
.load('current', { 'packages': ['corechart'], 'language':'no' });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Model.Avstemning.Tittel'],
['#Model.Avstemning.Option1', #Model.Avstemning.One],
['#Model.Avstemning.Option2', #Model.Avstemning.Two],
['#Model.Avstemning.Option3', #Model.Avstemning.Three]
]);
var options = {
title: '#Model.Avstemning.Tittel'};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
}
If I change the data variable to take hard coded options with norwegian letters it works. But that's not exactly ideal. Any ideas on how to solve this? Inject javascript from controller?
I solved the encoding issue by using Html.Raw(). Not recommended if these are later to be stored in db, but works for displaying the data as I intended:
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Html.Raw(Model.Avstemning.Tittel)'],
['#Html.Raw(Model.Avstemning.Option1)', #Model.Avstemning.One],
['#Html.Raw(Model.Avstemning.Option2)', #Model.Avstemning.Two],
['#Html.Raw(Model.Avstemning.Option3)', #Model.Avstemning.Three]
]);
var options = {
title: '#Html.Raw(Model.Avstemning.Tittel)',
};

How to properly pass json to a view

I have a view with some javascript code for a pie chart in it. This view has an action method, where I am running some queries an converting the results to json in order to fill the pie chart with something.
The problem is that I don't know (and couldn't understand from another questions here) how to properly return a json from action to view and actually work with the data in some way in the view.
Currently, what I have give me a json string in my browser instead of a view.
I do not have a model in my project for the data that's in in the json.
Here's all the code from my view :
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['German', 5.85],
['French', 1.66],
['Italian', 0.316],
['Romansh', 0.0791]
]);
var options = {
legend: 'none',
pieSliceText: 'label',
title: 'Accumulated experience',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<div id="piechart" style="width: 1000px; height: 600px;"></div>
And here is my controller :
public ActionResult experiencePieChart()
{
//some queries
var json = JsonConvert.SerializeObject(perclist);
return Json(json, JsonRequestBehavior.AllowGet);
}
your controller method should return JsonResult, just change it's signature in following way:
public JsonResult experiencePieChart()
{
var perclist = ...
//some queries
return Json(perclist, JsonRequestBehavior.AllowGet);
}
then in your js code you could call it
$(document).ready(function()
{
$.get("/YourController/experiencePieChart",ShowPieChart,"json").fail(ShowPieChartFail);
});
of course then you need define ShowPieChart function which will render that graph
function ShowPieChart(chartData){
// this code will be executed after result is returned asynchronously
// chartData contains JSON representation of perclist variable
}
In case you'd like to do that data-transfer just on each refresh of page, you could store data required for chart. In your .cshtml you'd just add
<script type="text/javascript">
var ChartData = #Html.Raw(Json.Encode(#Model.MyData))
</script>
then during execution of js on client side you'd have ChartData variable initialized. Anyway this way have multiple downside and is not scalable at all. Going with ajax call seems much better to me.

Stacked Chart with the wrong type of data with Google Chart API

I am in a trouble that the stacked chart in the left side runs well with JSFiddle. However, that code did not run with my ASP.NET. Here are the error and code. Please let me know how to address this problem.
You called the draw() method with the wrong type of data rather than a DataTable or DataView×
JSFIDDLE: http://jsfiddle.net/huydq91/pu5wbgpv/3/
<div id="div_id"></div>
<script type='text/javascript' src='https://www.google.com/jsapi?ext.js'>
</script><script type=text/javascript>
google.load('visualization', '1.1', {packages:['bar']});
google.setOnLoadCallback(drawChart);
function drawChart(){
var data = google.visualization.arrayToDataTable([['Month','Target Shipment','Actual Shipment'],['JAN',1053355,482899],['FEB',322087,468206],]);
var view = new google.visualization.DataView(data);
var options = { };
var chart = new google.charts.Bar(document.getElementById('div_id'));
chart.draw(view, google.charts.Bar.convertOptions(options));
}
</script>

object Object does not fit the Control specification

I am trying to debug this code and i tried to follow an example that works perfectly and i can get the chart and graphs to display without wrapper but once i make the change it falls apart ----[object Object] does not fit the Control specification.
WORKING code that puts all 3 on same view:
Project 1: Spreadsheet display working
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart', 'table']
});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(sendQuery);
// Construct and send a query to Google Spreadsheet
function sendQuery() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Ixlanep_0VfZtnk4rzS0jb1owTIbIRWAdGr9mp7OMIc/gviz/tq?tq=');
//query.setQuery('SELECT E, F, H, I');
query.send(drawChart);
}
// The query callback function
function drawChart(response) {
// Always check for error.
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
// Get DataTable from the "response" object. This is the result from your query.
// This DataTable must conform to the data format required by the chart you will draw next.
// To find out, read the Google Chart document at
// https://developers.google.com/chart/interactive/docs/
var data = response.getDataTable();
// Sort by the first column.
data.sort([{column: 0 }]);
//--------------------------------------------------------------------------
// Draw a table
//--------------------------------------------------------------------------
// We'll show the whole table. So there is no need to set call setColumns().
var tableView = new google.visualization.DataView(data);
// Create the table.
// Note that DOM element ID must be consistent with the corresponding
// ID in the HTML body section.
var myTable = new google.visualization.Table(document.getElementById('table_div'));
myTable.draw(tableView);
//--------------------------------------------------------------------------
// Draw a chart #1
//--------------------------------------------------------------------------
// Create the chart #1.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins, loses, and NO# games behind .
var chartView = new google.visualization.DataView(data);
chartView.setColumns([4, 5]);
// Create the chart.
// Note that DOM element ID must be consistent with the corresponding
// ID in the HTML body section.
var myChart = new google.visualization.ColumnChart(document.getElementById('chart1_div'));
myChart.draw(chartView);
//--------------------------------------------------------------------------
// Draw a chart #2
//--------------------------------------------------------------------------
// Create the chart #2.
// Note that DOM element ID must be consistent with the corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins, loses, and NO# games behind .
var chartView2 = new google.visualization.DataView(data);
chartView2.setColumns([0, 7, 8, 9]);
// Create the chart #2.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
var myChart2 = new google.visualization.
ColumnChart(document.getElementById('chart2_div'));
myChart2.draw(chartView2);
}
</script>
</head>
<body>
<h2>Project 1: Spreadsheet display working</h2>
<!--Div that will hold the pie chart-->
<div id="table_div"></div>
<div id="chart1_div"></div>
<div id="chart2_div"></div>
</body>
</html>
PROBLEM CODE
<html>
<head>
<title>Project 1: Spreadsheet display working</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['controls', 'map',
'table', 'corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(sendQuery);
// Construct and send a query to Google Spreadsheet
function sendQuery() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Ixlanep_0VfZtnk4rzS0jb1owTIbIRWAdGr9mp7
OMIc/gviz/tq?tq=');
//query.setQuery('SELECT E, F, H, I');
query.send(drawChart);
}
// The query callback function
function drawChart(response) {
// Always check for error.
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' +
response.getDetailedMessage());
return;
}
var data = response.getDataTable();
// Sort by the first column.
data.sort([{column: 0 }]);
//------------------------------------------------------------------
// Draw a table
//------------------------------------------------------------------
// We'll show the whole table. So there is no need to set call
setColumns().
var tableView = new google.visualization.DataView(data);
// Create an empty ChartWrapper and set its properties
var chart1 = new google.visualization.ChartWrapper();
chart1.setChartType('Table');
chart1.setContainerId('table_div');
// To set a DataView for the ChartWrapper, use
DataView.toJSON()function.
// There is a no need to set DataTable for the ChartWrapper.
chart1.setView(tableView.toJSON());
//------------------------------------------------------------------
// Draw a chart #1
//------------------------------------------------------------------
// Create the chart #1.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins,
loses, and NO# games behind .
var chartView = new google.visualization.DataView(data);
chartView.setColumns([4, 5]);
var chart2 = new google.visualization.ChartWrapper();
chart2.setChartType('ColumnChart');
chart2.setContainerId('chart1_div');
chart2.setView(chartView.toJSON());
// Create the chart.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
//var myChart = new
google.visualization.ColumnChart(document.getElementById('chart1_div'));
//myChart.draw(chartView);
//------------------------------------------------------------------
// Draw a chart #2
//------------------------------------------------------------------
// Create the chart #2.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins,
loses, and NO# games behind .
var chartView2 = new google.visualization.DataView(data);
chartView2.setColumns([0, 7, 8, 9]);
var chart3 = new google.visualization.ChartWrapper();
chart3.setChartType('ColumnChart');
chart3.setContainerId('chart2_div');
chart3.setView(chartView2.toJSON());
// Create the chart #2.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
//var myChart2 = new
google.visualization.ColumnChart(document.getElementById('chart2_div'));
//myChart2.draw(chartView2);
// Create and draw the dashboard
var dashboard = new
google.visualization.Dashboard(document.getElementById('dashboard_div'));
// Bind the filters to charts. These filters and charts now become
part of this dashboard.
dashboard.bind([chart1, chart2, chart3]);
// Draw all the charts and filters in this dashboard.
dashboard.draw(data);
}
</script>
</head>
<body>
<h2>Project 1: Spreadsheet display working</h2>
<div id="dashboard_div">
<table>
<tr>
<td>
<!--Div that will hold the pie chart-->
<div id="table_div" style="height: 200px; width: 1000px;
border-style: groove;">
</div>
<br />
<div id="chart1_div" style="height: 200px; width: 1000px;
border-style: groove;">
</div>
<br />
<div id="chart2_div" style="height: 200px; width: 1000px;
border-style: groove;">
</div>
</td>
</tr>
</table>
</div>
</body>
</html>

unable to load google chart from another html file using AJAX

Im building a simple web page presenting a simple google pie chart according to data passed with JSstorage. the chart is located in another html file. Im trying to populate a div with the chart using AJAX.
the button that activates the drawing process:
<input type="button" name="showChart" value="Show Chart" onclick="drawChart()">
the div that will be populated with the chart:
<div id="placeForChart" style="width:800; height:700">
google chart goes here
</div>
the function that being called upon button click :
function drawChart()
{
$.jStorage.set("costsArr",costsArr);
document.getElementById('placeForChart'.innerHTML = loadChart('chart.html'));
function loadChart(href)
{
console.log("load chart function was called..");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseXML;
}
}
and finally the chart.html, which is pretty much the standard google's example, with modified content passed using JSstorage.
<head>
<script type="text/javascript">
var costsArr = $.jStorage.get('costsArr');
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['food', costsArr[0]],
['clothes', costsArr[2]],
['house holds', costsArr[1]],
['other', costsArr[3]]
]);
var options = {'title':'your expenses',
'width':500,
'height':400};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
This line will throw a syntax error:
document.getElementById('placeForChart'.innerHTML = loadChart('chart.html'));
Your closing parenthesis for the getElementById call is in the wrong place. It should be:
document.getElementById('placeForChart').innerHTML = loadChart('chart.html');
I suspect that you will need to strip any <html>, <head>, and <body> tags from chart.html. Also, you should probably load the visualization API on your main page and use a load event handler in chart.html to draw the chart.

Categories

Resources