How to properly pass json to a view - javascript

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.

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

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!

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>

Uncaught SyntaxError: Unexpected token & while rendering a Django template

I'm trying to draw a line chart using "https://www.google.com/jsapi", and passing data from a Django view;
this is my template
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
data = {{analytics_data}}
var data = google.visualization.arrayToDataTable(data);
var options = {
title: 'Facebook Analytics'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
views.py
def show_fb_analytics(request):
analytics_data = [["Day", "Likes", "Share", "Comments"]]
data = FbAnalytics.objects.all()
for item in data:
date = item.date
likes = item.likes
comments = item.comments
shares = item.shares
lst = [date, likes, comments, shares]
analytics_data.append(lst)
return render(request, 'fbchart.html', {'analytics_data':analytics_data})
The analytics_data should return data in format
[['Day', 'Likes', 'Share', 'Comments'],
['31 Aug', 5, 8, 10 ],
['01 Sep', 10, 5, 13 ]]
but during render of the html template it gives data it given format
[['Day', 'Likes', 'Share', 'Comments'],
[u'01Sep', 2, 2, 2]]
means it is adding u'&#39 in every string due to which I'm getting the error "Uncaught Syntax Error: Unexpected token &" and my temlate is not returning the line chart.
How I can remove this error?
You should convert your list to proper JSON first, like this:
import json
def show_fb_analytics(request):
...
return render(request, 'fbchart.html', {'analytics_data': json.dumps(analytics_data)})
Then output it with "safe" filter, so Django's escaping engine doesn't intervene:
{{analytics_data|safe}}
Converting to JSON will output your list as JavaScript Array literal (instead of Python List literal; although the two are pretty similar, they are in fact different, in your case Python has u prefixes which JS doesn't, etc.), and using safe filter will prevent Django's template engine from converting ' to '
#Spc_555's answer is correct but you can mark the JSON as safe in the view too:
import json
from django.utils.safestring import marksafe
def show_fb_analytics(request):
...
return render(request, 'fbchart.html', {'analytics_data': mark_safe(json.dumps(analytics_data))})

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