I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables to make them compatible with the Google code.
In my attempts, I encountered an error while using the following code:
var zipie = <%= zip1 %>;
The error message stated that
zip1 cannot be resolved to a variable
. Directly calling my Java variable in the JavaScript code did not yield the desired outcome.
<script type="text/javascript">
google.load('visualization', '1', {
'packages' : [ 'corechart' ]
});
<%
try {
PieChartDAO pDao = new PieChartDAO();
String sql = PieChartSQLCreation.getTopZipCode();
ResultSet zipr = pDao.getTopZip(sql);
int[] zip = new int[5];
String[] zips = new String[5];
for(int i = 0; i < 5; i++) {
zip[i] = zipr.getInt("num");
zips[i] = zipr.getString("zip_code");
zipr.next();
}
int zip1 = zip[0];
}
catch (Exception e) {
e.printStackTrace();
}
%>
var zipie = <%= zip1 %>;
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
visualization_data = new google.visualization.DataTable();
visualization_data.addColumn('string', 'Zip Code');
visualization_data.addColumn('number', 'Number of Students');
visualization_data.addRow(['Work', zipie]);
visualization_data.addRow(['Eat', 2]);
visualization_data.addRow(['Commute', 2]);
visualization_data.addRow(['Watch TV', 2]);
visualization_data.addRow(['Sleep',7]);
visualization = new google.visualization.PieChart(
document.getElementById('piechart'));
visualization.draw(visualization_data, {
title : 'Zip Codes',
height : 260
});
}
</script>