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)
);
Related
I have a table Trailers which contain trailers and the number of views of a trailer.Here i passed data from table Trailers to view using ViewBag and i want to draw a google chart using this data in viewbag but i have no idea about how to convert datas in viewbag to array required to draw chart in javascript
Here is the code used in javascript
<script type="text/javascript">
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Views per Day'],
#foreach(var t in ViewBag.trailer)
{
[t.mov_name, t.count],
}
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
I don'know how to insert datas in ViewBag to the variable data.
Please help me
You can do it like below
var trailers = #Html.Raw(ViewBag.trailer);
var data = google.visualization.arrayToDataTable(['Task', 'Views per Day'], trailers);
May be you need to properly manipulate trailer object before passing it to parameter.
Html.Raw() will resolve your issue.
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.
Fiddle
I created this fiddle but when try getImageURI() from chart (orgchart google charts) one error is generated.
ERROR: "Uncaught TypeError: chart.getImageURI is not a function"
I need to generate an image or a PDF from orgchart created. Is it possible?
google.charts.load('current', {packages:["corechart","orgchart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
// For each orgchart box, provide the name, manager, and tooltip to show.
data.addRows([
[{v:'Mike', f:'Mike<div style="color:red; font-style:italic">President</div>'},
'', 'The President'],
[{v:'Jim', f:'Jim<div style="color:red; font-style:italic">Vice President</div>'},
'Mike', 'VP'],
['Alice', 'Mike', ''],
['Bob', 'Jim', 'Bob Sponge'],
['Carol', 'Bob', '']
]);
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
$( "#chart_div2" ).append( '<img src="' + chart.getImageURI() + '">' );
});
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {allowHtml:true});
}
similar to Table Charts, Org charts produce HTML <table> elements, rather than SVG
which is why getImageURI isn't listed in the Methods section for either chart
recommend using library to convert the HTML to Canvas (html2canvas.js),
which can then be saved as base64 string,
similar to getImageURI
see this answer, for a little more info on the topic...
Rendering HTML elements to canvas
try this code:
function printImg() {
html2canvas($('#chart_div').get(0)).then( function (canvas) {
var image = convertCanvasToImage(canvas);
var htmlToPrint = image.outerHTML ;
newWin = window.open("");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
});
}
Don't forget to include html2canvas.js
I am working on a UI where a user chooses both a start and end dates in order to retrieve data. Some of these data are shown in tables and I want to show a google chart related to those data displayed.
When the user finally chooses the dates, i send these two variables by using the $.post() function as follows:
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
$('#button-send').click(function() {
var url_route = "{{URL::action('Controller#general_stats_post')}}";
var start_date=$('#start_date_i').val();
var end_date=$('#end_date_i').val();
var datos = {start_date: start_date, end_date:end_date,_token:_token};
Once the send button is clicked, i use the $.post() function which works fine:
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*Here goes the google chart*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
The events_types string is, for example:
[['Event','Total'],['Workshop',1],['Seminar',1]]
which perfectly works in google's jsfiddles.
So, what i have been trying is to put the google chart's drawChart() function inside the {} where the string events_types does exist as follows:
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*GOOGLE CHART*/
google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(response.events_types);
var options = {
title: 'My test'
};
var chart = new google.visualization.PieChart(document.getElementById('eventos_charts'));
chart.draw(data, options);
}
/*END OF GOOGLE CHART PART*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
I have put a console.log message to let me know that the drawChart() has been run. However, I never get that message. So this means the drawChart() function is never run :/ I am stuck.
Almost working - EDIT
This is the code that is working... but only if I define the data string manually, that is to say:
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable([['Evento','Cantidad'],['Taller',1],['Seminario',1]]);//DEFINED MANUALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to #FABRICATOR
/**** END Google charts: Events types *********/
}
However, if i tried to get the data dynamically:
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(the_string);//DEFINED DYNAMICALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to #FABRICATOR
/**** END Google charts: Events types *********/
}
I get the following error:
Uncaught Error: Not an array
Any ideas to make it work? What am I missing?
Finally I have found the easiest solution.
Given that I am using Laravel's ORM (Illuminate/Database), the gotten data comes in json format.
This works for Laravel and Slim framework.
So I pass the variables directly to the view (in Slim):
$app->render('home.php',[
'myArray'=>$myArray
]);
Then, inside the view (in this case, Twig view. It should be similar in blade), I get the array and put it in a variable inside the Javascript code:
var myArray = {{ myArray|json_encode|raw }};
Then I iterate to get each element and add it into the Google chart data array:
$.each(myArray,function(index, value){
//console.log('My array has at position ' + index + ', this value: ' + value.r1);
data.addRow([value.col1,value.col2,value.col3,value.col4]);
});
And it works now.
I am using a Google Pie Chart in my website to show some data of company expenses. The chart gives me nice tooltips as I hover over the slices. It says for example 27% and gives the number of expense as 522552225.00 for example. What I would like to do is to get the number formatted as it is hard to read when the number is large. I would like to have this instead 522,552,225.00.
The problem is that the number comes from database.
Is there a solution to this?
Thanks!
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Label","Value"],
<?php echo $MyDataArrayAsString; ?>
]);
var formatter = new google.visualization.NumberFormat({pattern:'#,###.00'});
// format column 1 of DataTable "data"
formatter.format(data, 2);
var options = {"width":<?php echo $params->get('width')?>,
"height":<?php echo $params->get('height')?>,
"tooltip": {"trigger": '<?php echo $params->get('tooltip')?>' },
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
Use a NumberFormatter on the appropriate DataTable column:
var formatter = new google.visualization.NumberFormat({pattern: '#,###.00'});
// format column 1 of DataTable "data"
formatter.format(data, 1);