Why can't I add data to my google pie chart?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
foreach($piechartcaloy as $value){
echo "['".$value['product_name']."',".$value['TEST']."],";
}
?>
]);
var options = {
title: 'TOP 10 products'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}
it vanished the pie chart when i add the
<?php
foreach($piechartcaloy as $value){
echo "['".$value['product_name']."',".$value['TEST']."],";
}
?>
but if i add a normal
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['test',1]
]);
it work but why does my php does not working although i tried to print_r($data);die; my data array it shows like this
Array ( [piechartcaloy] => Array ( [0] => Array ( [product_name] => REG Okinawa [TEST] => 1 ) [1] => Array ( [product_name] => French Fries [TEST] => 0 ) ) )
It has values in it but why can't I populate it? What is wrong in my loop in the pie chart?
i already solved the answer and noticed that the array was having a space so i tried using trim(); and it works trim removes extra spaces that fix the problem.
here is the code i implement
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
foreach($piechartcaloy as $value){
echo "['".trim($value['product_name'])."',".trim($value['TEST'])."],";
}
?>
]);
var options = {
title: 'TOP 10 Fast Moving products'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}
Related
I'm building pizzeria app in CI using cart library.
For some products (pizza, salad...) there is an option to add ingredients.
This is what I have:
Add_to _cart buton
<button class="but_add_cart"
data-qty="1"
data-productid="<?php echo $food_item->item_id; ?>"
data-productname="<?php echo $food_item->item_name; ?>"
data-productprice="<?php echo $food_item->item_price; ?>"
data-adds="<?php echo $food_item->item_price; ?>
With jquery I'm calling ajax
$('.but_add_cart').click(function(){
allVals = []
$('#chk :checked').each(function() {
allVals.push($(this).val());
});
// here I'm getting all ingredients from checkboxes and push to array
var product_id = $(this).data("productid");
var description = $(this).data("description");
var product_name = $(this).data("productname");
var product_price = $(this).data("productprice");
var product_qty = $(this).data("qty");
if(product_id != '' && product_id > 0)
{
$.ajax({
url:"<?php echo base_url(); ?>menu/add",
type:"POST",
async: true,
data:{product_id:product_id, description:description, product_name:product_name, product_qty:product_qty, product_price:product_price, allVals:allVals},
success:function(data)
{
$('#cart_details').html(data);
}
});
}
else
{
alert("Please Enter quantity");
}
});
and add function is:
function add()
{
$data = array(
"id" => $_POST["product_id"],
"qty" => $_POST["product_qty"],
"price" => $_POST["product_price"],
"name" => $_POST["product_name"],
"description" => $_POST["description"],
"allVals" => $_POST["allVals"]
);
print_r($data);
//$this->cart->insert($data);
//echo $this->view();
}
from print_r I have this array
Array
(
[id] => 1
[qty] => 1
[price] => 19.90
[name] => Pepperoni Pizza
[description] => Extra-virgin olive oil, garlic, mozzarella cheese
[allVals] => Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 6
)
)
Now, in the cart, I want to group Pepperoni pizza with ingredients (2, 3, 4, 6) as one item. If I add one more Pepperoni pizza but with different ingredients, it should be separate item in the cart. I tried to add some random number to rowid but it gives me some error.
Also, every ingredients coast so I have to add these prices to subtotal price for each item in the basket.
I know problem is quite complex but I would like to know if my approach is good or there is a better way to to do this?
Is the answer here not to use the ingredients as the key?
asort($_POST['allVals']);
$key = implode('',$_POST['allVals']);
Combine the Product ID and $key and see if that product exists in the cart. If it does then update the quantity. Your ingredients are your unique key?
I'm trying to take a array from PHP code returned from my CodeIgniter model/controllers and display at my page view. But, the chart is not generated, maybe because it's not getting the right data.
Here's my code:
<?php
$data = array(
$generateChart['A'],
$generateChart['B']
);
json_encode($data);
?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('string', 'city');
data.addColumn('string', 'date');
data.addRows(<?php echo $data; ?>);
var options = {
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<div class="row">
<div id="piechart" style="width: 900px; height: 500px;" class="col-md-4">
</div>
If I send this: I receive the data everything fine!
Created a new question more specific about my problem: Google Charts won't work if passing JSON data but works with fixed data
couple things...
see the data format for PieChart
first column should be 'string'
second a 'number'
'date' column is invalid
the array format from the comment won't work
you need an array for each row, which should have a value for each column
something like...
Array(
[0] => Array(
[0] => 10 - TATUÍ
[1] => 12
)
[1] => Array(
[0] => 1 - CONCÓRDIA
[1] => 13
)
[2] => Array(
[0] => 928 - PONTA GROSSA
[1] => 14
)
)
I am trying to plot two different time series using annotated timeline and PHP by adding roles - the second timeseries will have its own datetime type and role domain. Here is the index.php file:
<script type='text/javascript'>
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChartSeptTEC);
function drawChartSeptTEC(){
var json = $.ajax({
url: "get_json_forecast.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(json);
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
}
// setInterval(drawChartSeptTEC, 59000 );
</script>
and the server side:
<?php
$tempcols=array();
$tempcols[] =array('type' => 'datetime','role' => 'domain');
$tempcols[] =array('type' => 'number','role' => 'data','label'=>'polynomial');
$tempcols[] =array('type' => 'number','role' => 'interval');
$tempcols[] =array('type' => 'number','role' => 'interval');
$tempcols[] =array('type' => 'datetime','role' => 'domain');
$tempcols[] =array('type' => 'number','role' => 'data','label'=>'spectral');
$table['cols'] = $tempcols;
$rows = array();
$pg_result = pg_query($link,$query);
pg_close($link);
while ($row = pg_fetch_assoc($pg_result)) {
$temp = array();
$correctDateTime = substr_replace($row['time'], ( substr($row['time'],5,2) -1 ) ,5,2);
$temp[] = array('v' => "Date(".$correctDateTime.")");
$temp[] = array('v' => (float) $row['f2poly']);
$temp[] = array('v' => (float) $row['f2polydev']);
$temp[] = array('v' => (float) $row['f2polydev']);
$temp[] = array('v' => "Date(".$correctDateTime.")");
$temp[] = array('v' => (float) $row['f2spec']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
echo $jsonTable;
?>
The console error reports:
Error: each values column may be followed by one or two annotation columns. Column number 4 is of type datetime.
The visualisation works when I remove the second domain column.
The interval roles (that is the error bars) are not recognised as well. Which simplifies the question to: How do we configure roles using PHP?
annotated time line does not support roles. In order to achive the result, one needs to use another visualisation, for example:
....
google.load('visualization', '1', {'packages':['corechart']});
....
and to plot the data:
...
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
...
however, this chart does not support a second domain role, therefore you need to use one domain (or independent variable, say the x-axis) and use for y-values null if the domain x-values have no corresponding y-value for both data sets. In this case, and if you want to use lines, you need to set the option:
interpolateNulls: true,
in your draw() function.
Another option is to use dygraph which is faster than line chart.
Fetch Data from Oracle:
echo "<br/>Self User data<br/>";
$curs = oci_new_cursor($conn);
$varin1 = "111"; //employee_id
$varin2 = "FEB-2015"; //month_year
$varin3 = "1";
$stid = oci_parse($conn, "begin WEEKLY_EMPLOYEE_DETAILS(:varIn1,:varIn2,:cursbv); end;");
oci_bind_by_name($stid, ":varIn1", $varin1);
oci_bind_by_name($stid, ":varIn2", $varin2);
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);
oci_execute($curs); // Execute the REF CURSOR like a normal statement id
echo "<pre>";
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
print_r($row) . "<br />\n";
}
oci_free_statement($stid);
oci_free_statement($curs);
Ouput of above code:
Self User data
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 24
[STATUS] => 1
[WEEK_ID] => 2
)
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 20
[STATUS] => 2
[WEEK_ID] => 3
)
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 40
[STATUS] => 2
[WEEK_ID] => 4
)
Google Pie chart Code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Work', 'Hours per Day'],
['Week 1', 25],
['Week 2', 25],
['Week 3', 25],
['Week 4', 25]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
How can I show the data fetched in form of pie chart. If there are 5 weeks in a month it will display the pie chart slice likewise. Along with it, it should also display hours for that week which are coming in array.
The pie chart looks great. You could pass the php variables to javascript and use them in the array.
var week1 = <?php echo json_encode($week1['TOTAL_HOURS']); ?>;
etc..
var data = google.visualization.arrayToDataTable([
['Work', 'Hours per Week'],
['Week 1', week1],
['Week 2', week2],
['Week 3', week3],
['Week 4', week4]
]);
It would be cleaner to put these variables in an array, and do a check first how many weeks there are in the month. You could do the same for the daily hours by fetching the daily employee details from the oracle database (if they exist).
To read more about passing variables to javascript:
How to pass variables and data from PHP to JavaScript?
I would like to get some help with coloring data differently in with google chart. I'm trying to compare two domains with date and rank value.
If I leave out the 'domain' data and just have date and value data, it will display a chart with the date data on the y-axis and the value data on the x-axis. I would like to use the domain data in my table to differentiate the data I'm comparing, one domain in one color vs. another domain in another color in a bar chart with the legend identifying the domain.
Basically using the code below I get the following error:
All series on a given axis must be of the same data type
If there's different and or easier way of going about this let me know.
Table Structure:
Column Type Null Default Comments
date text No
value text No
domain text No
Here's what I use to change my mysql data into Google friendly JSON:
<?php
/* $server = the IP address or network name of the server
* $userName = the user to log into the database with
* $password = the database account password
* $databaseName = the name of the database to pull data from
*/
$host="127.0.0.1"; //replace with your hostname
$username="XXXXXXX"; //replace with your username
$password="XXX"; //replace with your password
$db_name="KYW_data"; //replace with your database
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name") or die ("cannot select DB");
mysql_select_db($db_name, $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT date, value FROM KYW_Compete_rank');
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
array('label' => 'date', 'type' => 'string'),
array('label' => 'value', 'type' => 'number'),
array('label' => 'value', 'type' => 'string')
// etc...
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['date']);
$temp[] = array('v' => $r['value']);
$temp[] = array('v' => $r['domain']);
// etc...
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
Code for Displaying Google Chart:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "fetch.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Rank Standings",
width:600, height:400,
vAxis: {title: "Year and Month"},
hAxis: {title: "Rank"}}
);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="visualization"></div>
</body>
</html>
To get the legend to display two different series, you have to split your data into two columns. You can use SQL like this to split your data:
SELECT
date,
SUM(IF(<condition for series 1>, value, 0)) AS value_1,
SUM(IF(<condition for series 2>, value, 0)) AS value_2
FROM KYW_Compete_rank
GROUP BY date
and then populate your DataTable:
$table = array(
'cols' => array(
array('label' => 'date', 'type' => 'string'),
array('label' => 'value 1', 'type' => 'number'),
array('label' => 'value 2', 'type' => 'number')
)
'rows' => array()
);
while($r = mysql_fetch_assoc($query)) {
$data['rows'][] = array('c' => array(
array('v' => $r['date']),
array('v' => $r['value_1']),
array('v' => $r['value_2'])
));
}
echo json_encode($data, JSON_NUMERIC_CHECK);