Insert data from database to google chart codeigniter - javascript

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);
}

Related

How to draw chart using data in ViewBag in .net MVC5

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.

Google Chart Sorting vs Google Chart Editor

Please help! I am about to go insane over this! I have a Javascript for Google Chart that builds a table and a chart on the same dataset and when you sort the table the values on the chart get sorted as well. I also have a code that opens up the Google Charts Editor... which builds it's own chart. What I need is to merge these two functions. I need to build a table and a chart (that will get sorted as I sort the table) and when I open the Editor I need it to edit THAT chart (which will still be linked with sorting in the table) and NOT build a NEW chart.
Here are the 2 functions I have:
function drawSort() {
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var formatter = new google.visualization.NumberFormat({
prefix: '$'
});
formatter.format(data, 1); // Apply formatter to second column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var table = new google.visualization.Table(document.getElementById('table_s_div'));
table.draw(view);
var chart = new google.visualization.BarChart(document.getElementById('chart_s_div'));
chart.draw(view);
google.visualization.events.addListener(table, 'sort',
function (event) {
data.sort([{
column: event.column,
desc: !event.ascending
}]);
chart.draw(view);
});
}
var chartEditor = null;
function loadEditor() {
// Create the chart to edit.
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var wrapper = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: data,
options: {
'title': 'Number of Newly Opened Roles per <?echo $_SESSION['
Display ']?>',
'legend': 'none',
}
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {})
}
// On "OK" save the chart to a <div> on the page.
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_s_div'));
}

how to create a file inside the django template

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.

Google Charts Tooltip

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);

Not able to get getjson to work on highstock

I'm having some problems with importing a csv in order to get the highstock graph.
I'm using the same code as the ohlc example (which works fine locally) but with another CSV which is created on my localhost by php.
PHP to get the CSV
<?PHP
// Declare the new variable as an array
$arrCSV = array();
// Open the CSV file
if (($handle = fopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=7&e=7&f=2012&g=d&a=8&b=7&c=1984&ignore=.csv", "r")) !==FALSE)
{
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//print $c . "<BR>"; // <------ 7 o numero de colunas
//Populate the array
If ($key != 0) {
$arrCSV[$key-1][0] = strtotime($data[0])*1000; //Time
$arrCSV[$key-1][1] = $data[1]; //Open
$arrCSV[$key-1][2] = $data[2]; //High
$arrCSV[$key-1][3] = $data[3]; //Low
$arrCSV[$key-1][4] = $data[6]; //Adj Close
$arrCSV[$key-1][5] = $data[5]; //Volume
}
$key++;
} // end while
$keymax = $key;
// Close the CSV file
fclose($handle);
} // end if
print "?(/* AAPL historical OHLC data from the Google Finance API */<BR>";
echo json_encode($arrCSV,JSON_NUMERIC_CHECK);
print ");";
?>
Code to import and create the graph:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('http://localhost/teste03.php', function(data) {
console.log("1");
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 2
},
title : {
text : 'AAPL Stock Price'
},
series : [{
type : 'ohlc',
name : 'AAPL Stock Price',
data : data,
dataGrouping : {
units : [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
In the end it just get me a blank page...
On the chrome console I'm not able to get the console log that is inside the getjson and it reports as if everything is ok:
[23:39:29.980] GET http://localhost/TraderMananger/Highstock/ohlc4.htm [HTTP/1.1 304 Not Modified 1ms]
[23:39:30.036] GET http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js [HTTP/1.1 304 Not Modified 87ms]
[23:39:30.055] GET http://localhost/TraderMananger/Highstock/js/highstock.js [HTTP/1.1 304 Not Modified 1ms]
[23:39:30.073] GET http://localhost/TraderMananger/Highstock/js/modules/exporting.js [HTTP/1.1 304 Not Modified 1ms]
[23:39:30.219] GET http://localhost/TraderMananger/Highstock/teste04.php [HTTP/1.1 200 OK 2056ms]
Help?
Thanks
It is solved now, the issue was in the chos added before and after the json_encode, there is no need to add them
print "?(/* AAPL historical OHLC data from the Google Finance API */<BR>";
echo json_encode($arrCSV,JSON_NUMERIC_CHECK);
print ");";
So, removing them it solved the issue.

Categories

Resources