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.
Related
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
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)',
};
So I have a working google chart that uses a CSV file, parses the CSV data as a string into an array, and uses the array as the datatable.
I actually asked a question and answered it myself Here.
That link will show you a full chunk of code that I used in my full working website.
I intended to just pull the script from the test file and drop it into my website, but now that I've moved it over and included the scripts I needed, I'm getting an error as:
Type Error: $.csv is undefined
Here is the code where $.csv is being utilized (var arrayData), this is a function for drawing the chart
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="jquery.csv.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript"> // load the visualisation API
google.load('visualization', '1', { packages: ['corechart', 'controls'] });
</script>
<script type="text/javascript">
function drawVisualization() {
$.get("Thornton.M2.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// CAPACITY - En-route ATFM delay - YY - CHART
var crt_ertdlyYY = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'crt_ertdlyYY',
dataTable: data,
options:{
width: 450, height: 160,
title: 'EU-wide en-route ATFM delays (year to date)',
titleTextStyle : {color: 'grey', fontSize: 11},
}
});
crt_ertdlyYY.draw();
});
}
google.setOnLoadCallback(drawVisualization)
</script>
</head>
<body>
<div id="crt_ertdlyYY"></div>
</body>
This example works fully as you can see from the link I had posted before hand, if you wanted to test it. But now that I pull it into my main site the .csv calls do not recognize. I also have 2 other google charts on this page that still work properly so it's isolated to this issue. I'm very new to google charts and pretty confused here!
Have been trying to follow the guide here to creating a pie chart and from there develop some dashboard features in Google Apps Script. I found out that when you implement the calling of a script function (in the example it would be the drawChart() function), that is considered "Active Content" as seen here.
I have seen other examples that don't use HTML, but those all seem to require the use of the UiApp class, which has been depreciated. So, is the only way to get a dashboard/graphing feature in Google Apps Script to have an HTTPS security certificate? It seems rather limiting if this is the case. I see a post or two mentioning a similar frustration getting only a white screen, and I believe that is due to the HTTPS limitation.
Originally I didn't post code because I felt the issue here was pretty clear. Here is the code I have. I also tried a simple HTML "Hello World" file that didn't have any functions/scripts, and that worked. Here is the script as it relates to my Google Sheet:
function OpenChart(){
var html = HtmlService.createHtmlOutputFromFile('DummyChart');
SpreadsheetApp.getUi().showModalDialog(html, "Statistics");
}
Here is the HTML file it calls:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
//Load charts package and visualization API
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(MakeChart);
//Here is the script I think could be causing a problem
function MakeChart()
{
var ss = SpreadsheetApp.getActive();
var s = ss.getSheets();
var s = sheets[1];
var UI = SpreadsheetApp.getUi();
var response = UI.prompt("Please enter the first cell in the category").getResponseText();
var ir = s.getRange(response);
var n= 0;
var stored = [];
stored.push(["Income Category", "Frequency"]);
while (ir.getValue()!= "") {
n = n +1;
ir = ir.offset(1, 0);
}
//Above we just set n, below we use n to fill our array
ir = ir.offset(-n,0)
for(i =0; i<n;i++) {
stored.push([ir.getValue(),ir.offset(n+2,0).getValue()]);
ir = ir.offset(1, 0);
}
var data = google.visualization.arrayToDataTable([
stored[]]);
/*I tried to also load data here directly as is seen on the pie chart example I used. This didn't have any affect*/
var options = { 'chartArea:backgroundColor': "Azure",
'is3D': true,
'title': 'Test Chart'};
//Now instantiate it
var chart = new google.visualization.PieChart(document.getElementById('chartDiv'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chartDiv" style="width: 450px; height: 300px;"> </div>
</body>
</html>
Any help appreciated.
Here is a quick example of how this can work. I stuck with the basic example and added the values from the pie chart example to the spreadsheet. The client side will need to call the server side to get the data. The is done with google.script.run. You would modify getData() to suite your needs.
code.gs:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("charts").addItem("piechart", "openPieChart").addToUi()
}
function openPieChart(){
var html = HtmlService.createHtmlOutputFromFile("piechart");
var ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, "piechart")
}
function getData(){
return SpreadsheetApp.getActiveSheet().getDataRange().getValues()
}
piechart.html
<html>
<head>
<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(function(){google.script.run.withSuccessHandler(drawChart).getData()});
function drawChart(values) {
var data = google.visualization.arrayToDataTable(values);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
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>