Generating dynamic stats with google charts - javascript

I'd like to know whether it is possible to make simple and dynamic graphs with google charts; here what i am using actually:
Oracle DB, JSTL, EL, JSP pages.
What else should be in the sphere of my knowledge in order to realise the result mentioned above.
EDIT:
I'm going to gather data from the ORACLE databse through JPQL they will be stored in a list of Object[] containing a name and a number for each row, they will be sent a JSP page through servlet: request.setAttribute("data",listemployees);
How can acces to this list from the JSP and how do i store them in the javascript code generating the chart.
EDIT: Adding details
This is the DAO part, selecting the type of tickets and counting them.
private static final String JPQL_SELECT_TICKETS_ETAT = "SELECT t.etat, COUNT(t.id_ticket) FROM Ticket t GROUP BY t.etat";
#PersistenceContext( unitName = "bdd_helpdesk_PU" )
private EntityManager em;
public List<Object[]> chargerTicketsParEtat() throws DAOException {
List<Object[]> liste;
//List<Object[]> results = em.createQuery("").getResultList();
TypedQuery<Object[]> query = em.createQuery(JPQL_SELECT_TICKETS_ETAT, Object[].class);
//query.setParameter(PARAM_TICKET, id_ticket);
try {
liste = (List<Object[]>) query.getResultList();
} catch ( NoResultException e ) {
return null;
} catch(Exception e) {
throw new DAOException(e);
}
return liste;
}
Next code happens in servlet:
List<Object[]> lticket = ticketDao.chargerTicketsParEtat();
String test= "this is a string";
request.setAttribute("test", test);
request.setAttribute("lticket",lticket);
And this is the JSP page:
The result is represented in numbers in a table like this:
<table>
<tr>
<th>Etat ticket</th>
<th>Nombre</th>
</tr>
<c:forEach items="${lticket}" var="ticket">
<tr>
<td>${ticket[0]}</td>
<td>${ticket[1]}</td>
</tr>
</c:forEach>
</table>
And this is the kind of hart i'm going to use:
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
It is placed in head, I'd like to know what language should i use to be able to inject the data that is represented in the table into the chart's script, all i know is the EL ( expression langugae ) can't be placed in the script because it's interpreted in the server part while the js is interpreted by the browser
NEW SERVLET:`
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/json");
response.setHeader("Cache-Control", "nocache");
response.setCharacterEncoding("utf-8");
List<Object[]> lticket = ticketDao.chargerTicketsParEtat();
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
try{
json.put("status", 200);
json.put("msg", "OK");
JSONObject map = new JSONObject();
String nom="Non défini";
long valeur;
for (Object[] result : lticket) {
if((int)result[0]==1)
nom="En attente de prise en charge";
else if((int)result[0]==2)
nom="En attente de validation";
else if((int)result[0]==3)
nom="Cloturé";
else if((int)result[0]==4)
nom="En cours de traitement";
valeur = (long) result[1];
map.put(nom,valeur);
}
json.put("map", map);
}catch(JSONException e){
e.printStackTrace();
}
out.print(json.toString());
request.setAttribute("lticket", lticket);
this.getServletContext().getRequestDispatcher("/NewFile2.jsp").forward(request, response);
}
JSP PAGE:
`<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var jsonData = [];
$(document).ready(function(){
$.ajax({url: "/test", success: function(result){
jsonData = result.map;
}});
});
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
for (var key in jsonData) {
data.addRow([key,jsonData[key]]);
}
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="height: 300px; width: 100%;"></div>
</body>
`

For the DAO part you don't need to change anything.
For servlet you need to return a json like this :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class ChartsDataServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("application/json");
response.setHeader("Cache-Control", "nocache");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
try{
json.put("status", 200);
json.put("msg", "OK");
JSONObject map = new JSONObject();
map.put("Mushrooms", 3);
map.put("Onions", 1);
map.put("Olives", 1);
map.put("Zucchini", 1);
map.put("Pepperoni", 2);
json.put("map", map);
}catch(JSONException e){
e.printStackTrace();
}
out.print(json.toString());
}
}
And then use this servlet-url(say chartsDataUrl) on the page you want to draw the charts.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
var jsonData = [];
$(document).ready(function(){
$.ajax({url: "/chartsDataUrl", success: function(result){
jsonData = result.map;
}});
});
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
for (var key in jsonData) {
data.addRow([key,jsonData[key]]);
}
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Let me know if you have any questions.

Related

Google Annotation Chart load from CSV

I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:
https://developers.google.com/chart/interactive/docs/gallery/annotationchart
I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.
My code so far:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
$.get('test.csv', function(csvString)
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row)
{
return
[new Date(row[0]),row[1]];
});
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
CSV File
Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345
first, add jquery and jquery csv to your page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
then replace the code as follows.
see comments for explanations...
// load google charts
google.charts.load('current', {
packages: ['annotationchart']
}).then(function () {
// declare data variable
var arrayData;
// get csv data
$.get('test.csv', function(csvString) {
// get csv data success, convert to an array, draw chart
arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
drawChart(arrayData);
}).fail(function () {
// get csv data failed, draw chart with hard-coded data, for example purposes
arrayData = [
['Date','Value1'],
['2014-01-01',1233],
['2014-01-02',1334],
['2014-01-03',1488],
['2014-01-04',1888],
['2014-01-05',2011],
['2014-01-06',1900],
['2014-01-07',1768],
['2014-01-08',2345],
];
drawChart(arrayData);
});
});
// draw chart
function drawChart(arrayData) {
// convert string in first column to a date
arrayData = arrayData.map(function (row) {
return [new Date(row[0]),row[1]];
});
// create google data table, chart, and options
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
// draw chart
chart.draw(data, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: you can remove the fail callback, it is for example purposes here on stack overflow...
You need to follow 3 step for this task
Fire ajax request and take csv data
Convert csv data into array
Pass csv array in google graph
Please take refrence from following example:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
//Step 1: Get string from csv
$(document).ready(function () {
$.ajax({
type: "GET",
url: "test.csv",
dataType: "text",
success: function (data) {
//Step 2: Convert "," seprated string into array
let arrData = csvToArray(data);
//Step 3: call chart with array data
callChart(arrData);
}
});
});
//convert csv string into array function
function csvToArray(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1;i < allTextLines.length;i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0;j < headers.length;j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}
return lines;
}
function callChart(arrData) {
google.charts.load('current', { 'packages': ['annotationchart'] });
google.charts.setOnLoadCallback(function () { drawChart(arrData); });
}
function drawChart(arrData) {
var data = new google.visualization.DataTable();
//Step 4: add csv your column
data.addColumn('date', 'Date');
data.addColumn('number', 'Kepler-22b mission');
//Step 5: pass your csv data as array
data.addRows(arrData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>

Passing a C# variable value to a JavaScript variable in a script generated in code-behind class [duplicate]

This question already has answers here:
How do I give JavaScript variables data from ASP.NET variables?
(9 answers)
Closed 5 years ago.
I am trying to create an Asp.net app that displays a Google chart from data in an SQL database. Right now, I am just trying to pass the value of a C# int variable into a JavaScript variable. I'll figure out the rest later.
I have created the C# variable:
public int timcs = 40;
I try to create the JavaScript variable and display it in and alert box:
var timjs = '<%=timcs %>';
alert(timjs);
The resulting alert box just says <%=timcs %>.
If I do var timjs = <%=timcs %>; (no quotes) it doesn't work at all.
I have tried this many different ways and it never works. What am I doing wrong? All the code follows.
Thanks.
using System;
using System.Web.UI;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace TheBIGContest
{
public partial class _Default : System.Web.UI.Page
{
public int timsc = 40;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Bind Gridview
BindGvData();
// Bind Charts
BindChart();
}
}
private void BindGvData()
{
gvData.DataSource = GetChartData();
gvData.DataBind();
}
private void BindChart()
{
DataTable dsChartData = new DataTable();
StringBuilder strScript = new StringBuilder();
try
{
dsChartData = GetChartData();
strScript.Append(#"<script type='text/javascript'>
// Load the Visualization API and the corechart package.
google.charts.load('current', { 'packages': ['corechart'] });</script>
<script type='text/javascript'>
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
var timjs = '<%=timcs %>';
alert(timjs);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Person');
data.addColumn('number', 'Points');
data.addRows([ ['Tim', 10], ['Barb', 20], ['Lee Ann', 30] ]);");
//Set chart options
strScript.Append("var options = {'title':'Points to Date', chartArea: { left: 43, top: 50, width: '80 %', height: '80%' }, backgroundColor: 'fff', 'width': 610, 'height':450, 'vAxis': { minValue: 0, ticks: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]}, 'legend':'none'};");
// Instantiate and draw our chart, passing in some options.
strScript.Append("var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); chart.draw(data, options); }");
strScript.Append("</script>");
ltScripts.Text = strScript.ToString();
}
catch
{
}
finally
{
dsChartData.Dispose();
strScript.Clear();
}
}
/// <summary>
/// fetch data from mdf file saved in app_data
/// </summary>
/// <returns>DataTable</returns>
private DataTable GetChartData()
{
DataSet dsData = new DataSet();
try
{
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlDataAdapter sqlCmd = new SqlDataAdapter("GetData", sqlCon);
sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlCon.Open();
sqlCmd.Fill(dsData);
sqlCon.Close();
}
catch
{
throw;
}
return dsData.Tables[0];
}
}
}
The output tags <%= %> aren't relevant in this case because you are generating the client-side code from the code-behind class, rather than the actual aspx page.
Change to
var timjs = " + timcs + #"; ...
and it'll work.
its because you are using a literal string so its not executing the server side code. I would append the variable first in a separate .Append method without the literal (#). you could look at using interpolated and literal strings combined ($#) but you might need to escape some of the brackets etc.
private void BindChart()
{
DataTable dsChartData = new DataTable();
StringBuilder strScript = new StringBuilder();
try
{
dsChartData = GetChartData();
strScript.Append(#"<script type='text/javascript'>
// Load the Visualization API and the corechart package.
google.charts.load('current', { 'packages': ['corechart'] });</script>
<script type='text/javascript'>
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart); ");
strScript.Append($"var timjs = {timsc};");
strScript.Append(#"
alert(timjs);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Person');
data.addColumn('number', 'Points');
data.addRows([ ['Tim', 10], ['Barb', 20], ['Lee Ann', 30] ]);");
//Set chart options
strScript.Append("var options = {'title':'Points to Date', chartArea: { left: 43, top: 50, width: '80 %', height: '80%' }, backgroundColor: 'fff', 'width': 610, 'height':450, 'vAxis': { minValue: 0, ticks: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]}, 'legend':'none'};");
// Instantiate and draw our chart, passing in some options.
strScript.Append("var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); chart.draw(data, options); }");
strScript.Append("</script>");
ltScripts.Text = strScript.ToString();
}
catch
{
}
finally
{
dsChartData.Dispose();
strScript.Clear();
}
}

JSP x Google Charts X MySQL: Multiple Charts Not Displaying Entire Information

Good morning. I'm trying to make a dynamic web project in Java which connects to a MySQL database to retrieve certain information i need and display it in graphs using Google Charts. In this case, i'm trying to obtain two count values from the table post: number of posts by gender (whether Male or Female) and number of posts by location (whether East or West). Since i'm relatively new to this API, i practiced by displaying a single pie chart with the post count by gender and it works. It displays the number of posts whether the gender is male or female. However, when i try to display two charts (one pie chart with number of posts by gender and one column chart with number of posts by location), they load but they don't show the whole information. Instad of getting the number of posts for both genders and number of posts for both locations, i only get the number of posts for one gender ("Male") and the number of posts for one location ("West").
Here's a picture that illustrates what i'm trying to obtain and what i get instead: https://s31.postimg.org/40c3skgmz/output.jpg
I added some print lines in the JSP code to make sure it retrieves all the information i need and no problem there. However, that's not the case when i pass the data in the HTML.
Here's the JSP code for retrieving the data (using the JSON Library):
<%#page import="java.sql.*" %>
<%#page import="java.util.*" %>
<%#page import="org.json.JSONObject" %>
<%
Connection con= null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sentimentposts?autoReconnect=true&useSSL=false","root","root");
ResultSet rs1 = null;
ResultSet rs2 = null;
List opdetails = new LinkedList();
JSONObject responseObj = new JSONObject();
String query1 = "select poster_gender, count(*) as gender_count from post group by poster_gender";
PreparedStatement pstm1= con.prepareStatement(query1);
String query2 = "select poster_location, count(*) as location_count from post group by poster_location";
PreparedStatement pstm2= con.prepareStatement(query2);
rs1 = pstm1.executeQuery();
rs2 = pstm2.executeQuery();
JSONObject opObj = new JSONObject();
while (rs1.next()) {
String gender = rs1.getString("poster_gender");
System.out.println(gender);
int count = rs1.getInt("gender_count");
System.out.println(count);
opObj.put("gender", gender);
opObj.put("count", count);
}
while(rs2.next()){
String location = rs2.getString("poster_location");
System.out.println(location);
int count2 = rs2.getInt("location_count");
System.out.println(count2);
opObj.put("location", location);
opObj.put("count2", count2);
}
opdetails.add(opObj);
responseObj.put("opdetails", opdetails);
out.print(responseObj.toString());
}
catch(Exception e){
e.printStackTrace();
}finally{
if(con!= null){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
%>
The HTML code that displays the page:
<!DOCTYPE html>
<html>
<head>
<title>Opinion Chart Multi</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["corechart", "bar"], callback:drawCharts});
//google.setOnLoadCallback(drawCharts);
var queryObject="";
var queryObjectLen="";
$.ajax({
url : 'getdata.jsp',
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.opdetails.length;
},
error : function(xhr, type) {
alert('server error occoured')
}
});
function drawCharts() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'gender');
data.addColumn('number', 'gender_count');
for(var i=0;i<queryObjectLen;i++)
{
var gender = queryObject.opdetails[i].gender;
var count = queryObject.opdetails[i].count;
data.addRows([
[gender,parseInt(count)]
]);
}
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'location');
data2.addColumn('number', 'location_count');
for(var i=0;i<queryObjectLen;i++)
{
var location = queryObject.opdetails[i].location;
var count2 = queryObject.opdetails[i].count2;
data2.addRows([
[location,parseInt(count2)]
]);
}
var options = {
title: 'Posts By Gender',
};
var options2 = {
title: 'Posts by Location',
colors: ['green','yellow'],
hAxis: {
title: 'Location'
},
vAxis: {
title: 'No. of Posts'
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
chart1.draw(data,options);
var chart2 = new google.visualization.ColumnChart(document.getElementById('chart2'));
chart2.draw(data2,options2);
}
</script>
</head>
<body>
<table class="columns">
<tr>
<td><div id="chart1"></div></td>
<td><div id="chart2"></div></td>
</tr>
</table>
</body>
</html>
And finally, the format of the SQL table i'm using:
Table: post
Columns:
message varchar(45),
poster_age int(11),
poster_gender varchar(45),
poster_location varchar(45)
most likely, drawCharts is being called before the data is ready...
maybe try something like this...
google.load("visualization", "1.0", {
callback: function () {
var queryObject="";
var queryObjectLen="";
$.ajax({
url: 'getdata.jsp',
dataType: 'json',
success: function (data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.opdetails.length;
var data = new google.visualization.DataTable();
data.addColumn('string', 'gender');
data.addColumn('number', 'gender_count');
for(var i=0;i<queryObjectLen;i++) {
var gender = queryObject.opdetails[i].gender;
var count = queryObject.opdetails[i].count;
data.addRows([
[gender,parseInt(count)]
]);
}
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'location');
data2.addColumn('number', 'location_count');
for(var i=0;i<queryObjectLen;i++) {
var location = queryObject.opdetails[i].location;
var count2 = queryObject.opdetails[i].count2;
data2.addRows([
[location,parseInt(count2)]
]);
}
var options = {
title: 'Posts By Gender',
};
var options2 = {
title: 'Posts by Location',
colors: ['green','yellow'],
hAxis: {
title: 'Location'
},
vAxis: {
title: 'No. of Posts'
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
chart1.draw(data,options);
var chart2 = new google.visualization.ColumnChart(document.getElementById('chart2'));
chart2.draw(data2,options2);
},
error: function (xhr, type) {
alert('server error occoured')
}
});
},
packages:["corechart"]
});

Using PHP array in Google Charts

I have an array in my PHP code (budgetingMain.php) called "totals". I want to use it for my data to create a Google Pie Chart. However, I am having difficulty in encoding it.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var jsontotals = <?php echo json_encode($totals) ?>;
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Amount Spent on it');
data.addRows([
'jsontotals'
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chartcontainer'));
chart.draw(data, options);
}
</script>
In this current setup, I get the following error: "Uncaught SyntaxError: Unexpected token <" for this line.
var jsontotals = <?php echo json_encode($totals) ?>;
I realise it's an issue with the embedding, but I cannot find a way to get it to work. Any help welcome!
EDIT: This is the structure of totals
$totals = array(
array("ClothingAndAccessories",0),
array("FlowersAndDecorations",0),
array("Ceremony",0),
array("Reception",0),
array("Photography",0),
array("Gifts/favours",0),
array("Stationary",0),
array("Entertainment",0),
array("Other",0)
);

Google Visualization Charts ajax data

I'm trying to dynamically render a google visualization chart with an AJAX call in flask to set the data. User enters input then clicks a link which calls the ajax function to get the data. the "/ajax_test" view will return a json object but the problem I have is i don't know how to correctly pass the data back into the DataTable function. How do i pass the json data i'm getting from ajax to a variable for the drawchart function?
Chart function:
<script type="text/javascript">
function drawChart(){
var data = new google.visualization.DataTable(jsondata);
var options = {
explorer: {},
}; //end options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Ajax function:
<script type=text/javascript>
$(function() {
$('a#DrawChart').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/ajax_test',
{//input data sent to view}
, function(data) {
var jsondata = data.test_json;
drawChart();
});
return false;
});
});
</script>
This method doesn't know where jsondata comes from:
function drawChart() {
var data = new google.visualization.DataTable(jsondata);
...
}
Add jsondata as a parameter:
function drawChart(jsondata) {
var data = new google.visualization.DataTable(jsondata);
...
}
And then in your Ajax call pass jsondata to the method:
function(data) {
var jsondata = data.test_json;
drawChart(jsondata);
}
I have done something similar using the following code, this is a jinja2 example, so you have do adapt your code (change the way jsonData var is initialized):
<script type="text/javascript">
//load the Google Visualization API and the chart
google.load('visualization', '1', {'packages': ['corechart']});
google.setOnLoadCallback (createChart);
var jsonData = {{ value_columns | tojson | safe }}
function createChart() {
var dataTable = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//define options for visualization
var options = {is3D: 'no', title: 'Some Title' };
attachRedrawForTab(chart, dataTable, options);
attachRedrawForAccord(chart, dataTable, options);
//draw our chart
chart.draw(dataTable, options);
}
</script>

Categories

Resources