Files
railsgoat/app/views/dashboard/bar_graph.html.erb
T
Ken Johnson 8abf409041 Fix Google Charts loading for AJAX-loaded bar graph
The issue was that google.load() doesn't work reliably when called
from AJAX-loaded content. The callback wasn't firing.

Solution:
- Load Google Charts library once in main application.html.erb layout
- Bar graph partial now just polls for google.visualization to be ready
- Uses retry logic (50 attempts @ 100ms = 5 second timeout)
- Returns success/failure boolean for proper flow control
- Removed duplicate script loading from partial

This ensures Google Charts is available globally for all chart views
(bar graphs, pie charts, performance charts) without timing issues.

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

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

84 lines
1.9 KiB
Plaintext

<div id="column_chart"></div>
<script type="text/javascript">
function drawChart3() {
// Guard against calling before Google Charts is loaded
if (typeof google === 'undefined' || !google.visualization) {
console.warn('Google Charts not loaded yet, waiting...');
return false;
}
var chartElement = document.getElementById('column_chart');
if (!chartElement) {
console.warn('Chart element not found');
return false;
}
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);
console.log('Bar chart drawn successfully');
return true;
}
// Wait for Google Charts to be ready, then draw
function initBarChart() {
var attempts = 0;
var maxAttempts = 50; // 5 seconds max
var checkAndDraw = function() {
if (drawChart3()) {
// Success!
return;
}
attempts++;
if (attempts < maxAttempts) {
setTimeout(checkAndDraw, 100);
} else {
console.error('Failed to load Google Charts after ' + (maxAttempts * 100) + 'ms');
}
};
checkAndDraw();
}
// Initialize when partial loads
console.log('Bar chart partial loaded, waiting for Google Charts...');
initBarChart();
</script>