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.
Related
I want to insert data to get sales report from two table into google chart. I have tried join query in model page, but the result is No Data in pie chart div.
Data from table sales is like below
id | person_name | sales_id | status
1 Michael 2 1
2 Daniel 2 3
3 James 2 1
4 Ricky 1 2
5 Martin 1 3
The data from table status is like below
id | status | color
1 Meeting #f00630
2 Presentation #f2478f
3 Proposal Sent #170303
4 Invoice #7cb342
5 Lost #fe0725
I need to insert data status type, total status (in number), and color status into google pie chart based on sales id. I need to change data which I write manually like below
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
['Meeting', 2],
['Presentation', 0],
['Proposal Sent', 1],
['Invoice', 0],
['Lost', 0]
]);
var options = {
is3D: true,
colors: ['#f00630', '#f2478f', '#170303', '#7cb342', '#fe0725']
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Here is the script I have tried in model page
public function getAllStatus()
{
$this->db->select('status');
$this->db->from('sales');
$this->db->join('sales_status', 'sales_status.id = sales.status');
$this->db->where('sales_id', $id);
return $query = $this->db->get();
}
Here's script in controller page
$data['sales'] = $this->Sales_model->getAllStatus()->result();
And here's the script in view page
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
<?php
foreach ($sales as $sale){
echo "['".$sale->name."',".$sale->count."],";
}
?>
]);
<div id="chart_div" style="width: 100%; "></div>
Do you know where's I need to fix ?
Thank you
The chart expects JSON objects with the data. You can try to build JSON-like structures with loops like you did, but it's much simpler to just output the JSON objects.
In your view, before the call to the chart is made:
var first_data = <?php echo json_encode($your_first_var); ?>;
var second_data = <?php echo json_encode($your_second_var); ?>;
then, when you actually invoke the JS that will draw the chart:
function drawChart() {
var data = google.visualization.arrayToDataTable(first_data);
var options = {
is3D: true,
colors: second_data
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
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)
);
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>
i am generating the google charts and converting them into the image by using getimageuri() method. this method returns a url and now i need to store that url into file.
i dont know how to create a file inside the django template and how to store data into it.
following is my chart genearting code in javascript :
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart','table']});
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Job-Names', 'Pass', 'Fail'],
{{data.0.0|safe}}
]);
var options = {
title : 'Jenkins Job Details for project {{data.0.1}}',
vAxis: {title: "Job Names" , textStyle : {fontSize : 10} },
hAxis: {title: "Number of Builds" , ticks : [2,4,6,8,10] },
is3D: true,
width: 1250,
height: 550,
colors : ["#008000", "#cc0000"],
pointSize: 4
};
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
imageurl = chart.getImageURI()
});
chart.draw(data, options);
//var table = new google.visualization.Table(document.getElementById('table_div'));
//table.draw(data, {showRowNumber: false});
}
google.setOnLoadCallback(drawVisualization);
that imageurl i need to store into the file.
any help will be appreciated.
The getimageuri() actually return the file itself, uriencoded, which looks like:
data:image/png;base64,iVBORw0KGgoAA...
If you want to store this image server side, you have to send it to the server, preferably using AJAX, and then processing on server side by throwing away the text before the , including, and then creating an image file from the base64 string using django's File functions.
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);