Locale language for google charts not working - javascript

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

Related

Google Charts using CSV Data: $.csv is undefined?

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!

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.

Google Apps won't allow "Active Content" in HTML, and UiApp class has been depreciated

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>

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>

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