Files
railsgoat/app/views/dashboard/bar_graph.html.erb
T
Ken Johnson b47a70d8b8 Fix Google Charts race condition in bar graph view
The bar graph was calling drawChart3() before Google Charts library
finished loading, causing "Cannot read properties of undefined
(reading 'arrayToDataTable')" error.

Applied same fix as performance page:
- Check if visualization already loaded before calling google.load
- Use callback parameter to ensure charts only draw after load
- Add flag to prevent duplicate library loads
- Guard against missing DOM elements
- Handle AJAX-loaded partial context

Fixes dashboard statistics bar graph view errors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 02:27:06 -05:00

86 lines
2.2 KiB
Plaintext

<div id="column_chart"></div>
<!-- Google Visualization JS -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Prevent multiple initializations
if (typeof window.barChartLoaded === 'undefined') {
window.barChartLoaded = false;
}
function drawChart3() {
// Guard against calling before Google Charts is loaded
if (typeof google === 'undefined' || !google.visualization) {
console.warn('Google Charts not loaded yet');
return;
}
var chartElement = document.getElementById('column_chart');
if (!chartElement) {
console.warn('Chart element not found');
return;
}
var data = google.visualization.arrayToDataTable([
['Year', 'Visitors', 'Orders', 'Income', 'Expenses'],
['2007', 300, 800, 900, 300],
['2008', 1170, 860, 1220, 564],
['2009', 260, 1120, 2870, 2340],
['2010', 1030, 540, 3430, 1200],
['2011', 200, 700, 1700, 770],
['2012', 1170, 2160, 3920, 800]
]);
var options = {
width: 'auto',
height: '160',
backgroundColor: 'transparent',
colors: ['#b5799e', '#579da9', '#e26666', '#1e825e', '#dba26b'],
tooltip: {
textStyle: {
color: '#666666',
fontSize: 11
},
showColorCode: true
},
legend: {
textStyle: {
color: 'black',
fontSize: 12
}
},
chartArea: {
left: 60,
top: 10,
height: '80%'
},
};
var chart = new google.visualization.ColumnChart(chartElement);
chart.draw(data, options);
}
function initializeBarChart() {
// Check if Google Charts visualization is already loaded
if (typeof google !== 'undefined' && google.visualization && google.visualization.ColumnChart) {
drawChart3();
window.barChartLoaded = true;
} else if (typeof google !== 'undefined' && google.load && !window.barChartLoaded) {
// Load Google Charts
google.load("visualization", "1", {
packages: ["corechart"],
callback: function() {
drawChart3();
window.barChartLoaded = true;
}
});
} else {
console.error('Google JSAPI not available');
}
}
// Initialize immediately (page is already loaded when this partial loads via AJAX)
initializeBarChart();
</script>