Reputation: 2337
I've been working with Google charts with no problems but I've now got to a point where I need to display a chart inside of an Ajax-rendered partial.
Obviously nothing is showing. I know it's something to do with the Java trigger to build the chart not being activated, but I need some help with exactly what it is I need to do...
Currently I have something like this (non-Ajax):
<html>
<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() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Upvotes: 6
Views: 1663
Reputation: 2707
In your main page keep these (no need to load google charts in the partial):
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
</script>
In your partial you need to do something like below (assuming you use jQuery). The point is to execute the js code after the dom is loaded which is what $(function() {....}) does:
<div id="chart_div"></div>
<script type="text/javascript">
$(function() {
drawChart();
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Using a library like jQuery will save you many hours of browsers inconsistencies for knowing when the dom is properly loaded.
Upvotes: 8
Reputation: 384
Replacing
google.setOnLoadCallback(drawChart);
with
$(function() {
drawChart();
});
did the trick for the AJAX partials! Thanks for the help, previously the DOM was reloading but the charts weren't getting inserted.
Upvotes: 0