How to pass PHP arrays to Google Graph JavaScript function? - javascript

I am trying to output the contents of two arrays as the axis for a chart using Google's chart API.
I currently output the JavaScript function using PHP, which is where I feel the error is. I believe the script is just getting output but not running. I can see it has output in the correct format from the page source, however, no data is being shown on the window.
The following is the contents of my two arrays, which are just key and value pairs in separate arrays:
The following is my code in the HTML body, which I call in PHP in the same page:
<?php
function createChart($nutrientArr, $percentArr) {
$chart = "<script type='text/javascript'>
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', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([";
for($i = 0;$i < count($nutrientArr);$i++) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "'],";
if($i == count($nutrientArr) - 1) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "']";
}
}
$chart .= "]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>";
echo $chart;
}
?>
This is the source code:
<script type='text/javascript'>
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', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([['Calories', '18.32768'],['Fat', '23.065360824742'],['Saturated Fat', '22.640580645161'],['Monosaturated Fat', '25.274138888889'],['Polyunsaturated Fat', '23.481666666667'],['Carbohydrates', '8.6173573573574'],['Fiber', '17.975466666667'],['Sugar', '13.857878787879'],['Protein', '63.232972972973'],['Cholesterol', '37.102'],['Sodium', '7.8765666666667'],['Calcium', '13.39272'],['Magnesium', '20.481214285714'],['Potassium', '17.816553191489'],['Iron', '52.980375'],['Zinc', '25.689818181818'],['Phosphorus', '51.941142857143'],['Vitamin A', '13.804971428571'],['Vitamin C', '15.494555555556'],['Thiamin (B1)', '21.825333333333'],['Riboflavin (B2)', '23.152538461538'],['Niacin (B3)', '69.055'],['Vitamin B6', '63.236153846154'],['Folate Equivalent (Total)', '40.9758'],['Folate (Food)', '19.098075'],['Folic Acid', '0.8311225'],['Vitamin B12', '24.940875'],['Vitamin D', '2.1734733333333'],['Vitamin E', '13.491866666667'],['Vitamin K', '18.9045']]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I call the createChart() function in PHP at the top of the page, passing the two arrays.
I am looking to see what the best method of passing this data to the chart API is? Should I call the JS function from PHP and pass the arrays that way? I am not too familiar with JS so not sure how I would pass this data. Any help is very appreciated!
I have tried using json_encode and json_parse but neither work as I suspect I'm outputting the code at the wrong time or wrong way.

Related

how to add links to google pie chart slices and send that variable to new page once clicked

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var jsvar = '<?=$count?>';
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Rating'],
['Good', <?php echo $count; ?>],
['Average', <?php echo $count1; ?>],
['Bad', <?php echo $count2; ?>],
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Windoek' , 'width':400, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
window.open("table.php?myvar=" + encodeURI(selection));
});
I would like to get the selected task header and send it to new page ......
Example , If someone clicks the bad pie chart slice , The variable Bad and Title of pie chart should be send via link to new page for processing ....if someone selects Good than the variable Good with title of pie chart send to new page

Google Line Charts interpolateNulls: false breaks chart

I knew the answer was going to be much simpler then I was making it out to be. I added the following if statement to the while loop.
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
if($row["Year3"] == NULL ? $row["Year3"] = 'null' : $row["Year3"] = $row["Year3"]);
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
As an update we now know that the problem is MySql spits out NULL and javascript requires null. Any thoughts on how to accomplish getting MySql NULL int value into lowercase null.
*I was wondering if anyone can help me with this. I created a line chart to visual show company sales by month for the current year and the previous 2. It works fine, but because at this point there is 0 sales for the remaining months of the year it shows a steep drop off for that line. We don't want to see that, so I tried changing the 0s to nulls in the database and using interpolateNulls false. However when I add the interpolateNulls option the line chart breaks and no longer displays anything. Any ideas?
<script type="text/javascript">
var data;
var chart;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
data = google.visualization.arrayToDataTable([
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
]);
var options = {
backgroundColor: 'transparent',
title:'Total Sales By Month',
width:600,
height:500,
interpolateNulls: false,
legend: {position: 'bottom'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Can I access values generated by google charts

Currently I pass variables to the api like so:
<script type="text/javascript">
mobileNav();
// 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', 'Date');
data.addColumn('number', 'Attendance');
data.addRows([
['Present', <?php echo $present; ?>],
['Absent', <?php echo $absent; ?>],
['Directed Study', <?php echo $directed; ?>],
['Medical Certificate', <?php echo $medical; ?>],
['Self Certificate', <?php echo $selfcert; ?>],
['Authorised Absence', <?php echo $authorised; ?>],
]);
// Set chart options
var options = {'title':'Your Attendance'};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
I get the results and everything is good. I would like to access the % values generated by the pie chart. Is there a way this can be achieved?
If you want to access on your values generated by your pie chart , you need to retrieve data on your dataTable().
You need to use getFormattedValue method.
Documentation :
DataTable API : https://developers.google.com/chart/interactive/docs/reference#DataTable
Method : getFormattedValue(rowIndex, columnIndex)

Google Charts adding options to the charts

I am using this code for creating charts and it works but I need to add the options too just don't know where to add them.
<script type="text/javascript">
function drawVisualizationHourlyChart() {
var data = google.visualization.arrayToDataTable([ // Create and populate the data table.
['Date - Hour:Minute', 'Cares', 'Bikes', 'Both'],
<?php
while( $row = $result->fetch_assoc() ){
extract($row);
echo "['Date: ($dateandtime) - {$hour}:{$minute}', {$cars}, {$bikes}, {$both}],";
}
?>
]);
new google.visualization.LineChart(document.getElementById('mydiv')). // Create and draw the visualization.
draw(data, {legend: 'bottom', title:"titles here"});
}
google.setOnLoadCallback(drawVisualizationHourlyChart);
</script>
And what I want the do is add All the code below into the code above.
var options = {
//options go here
});
Where do I add the options?
The options are the second param of the draw method.
var options = {
legend: 'bottom',
title:"titles here"
};
chart.draw(data, options);

retrieve data from mongodb and visualize it with google charts

I'd like to retrieve data from database (mongodb) and with those data i'd like to draw à pie chart using google charts. in a first case i have a collection called user and each user has a boolean attribute called (paid), i'd like to count how many paid users and free users and basing on those results i will draw a pie chart with the percentage of each kind of users
this my try i tried with for a long time but i'dont arrive to show the chart,
thanks :)
<?php
$connection = new MongoClient();
$collection = $connection->pato->user;
$cursor = $collection->find();
$cursor = $collection->find(array("paid"=>true));
$x=$cursor->count();
$cursor = $collection->find(array("paid"=>false));
$y=$cursor->count();
$myurl[]="['Option','Value']";
$myurl[]=[['Free users', $y],['Paid users', $x]];
?>
<html>
<head>
<!--Load the AJAX API-->
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
// Set chart options
var options = {'title':'User statistics',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('userStatsDiv'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}</script>
<body>
<div id="usageStatsDiv" style="width:700; height:500"></div>
</body>
</html>
I think your problem is with your JSON:
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
It looks like you're trying to build the JSON string yourself. Let PHP do the work for you instead - use json_encode instead, like this:
var data=google.visualization.arrayToDataTable([
<?php echo json_encode($data); ?>
]);
You'll need to build your $data array so that it gives you the correct elements, but I think you'll find that the end result is cleaner and easier to understand.

Categories