retrieve data from mongodb and visualize it with google charts - javascript

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.

Related

How to pass PHP arrays to Google Graph JavaScript function?

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.

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

Problem with the appearance of geographical area points in map with google graph

I try to appear some geographical data as points (spots) in a global map.When i run the code -in the browser- are appearded the statistical results as text , the global map but on the they are not appeared.Itis must noted that the main code was taken from the code which implement the piechart.In the follow lines i present the code:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>plus2net.com : Pie chart using data from MySQL table</title>
</head>
<body >
<?Php
//
require "connection.php";// Database connection
if($stmt = $link->query("SELECT Nationality_Name,Count FROM nationality_arrivals")){
echo "No of records : ".$stmt->num_rows."<br>";
$php_data_array = Array(); // create PHP array
echo "<table>
<tr> <th>Nationality_Name</th><th>Count</th></tr>";
while ($row = $stmt->fetch_row()) {
echo "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
$php_data_array[] = $row; // Adding to array
}
echo "</table>";
}else{
echo $link->error;
}
//print_r( $php_data_array);
// You can display the json_encode output here.
echo json_encode($php_data_array);
// Transfor PHP array to JavaScript two dimensional array
echo "<script>
var my_2d = ".json_encode($php_data_array)."
</script>";
?>
<div id="chart_div"></div>
<br><br>
<a href=https://www.plus2net.com/php_tutorial/chart-database.php>Pie Chart from MySQL database</a>
</body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
<div id="chart_div"></div>
<br><br>
<a href=https://www.plus2net.com/php_tutorial/chart-database.php>Pie Chart from MySQL database</a>
</body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var data = google.visualization.arrayToDataTable([
['Nationality_Name','string'],['Count','number']
]);
var options = {title:'plus2net.com : How the tutorials are distributed',
width:600,height:500};
// Instantiate and draw the chart
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
}
</script>
</html>

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)

Once again about how to plot google chart after an ajax call

EDIT BEGIN
As I didn't receive any answer I'll try to explain or, better, show what worked to me (without ajax) and doesn't work now when I try to use ajax. As examples say more than words I'll write down the essencial parts of the codes.
I had two files, namely index.php where is the input form and where the chart is plotted and script.php that receives what was inserted in the form, makes a query with it and return a variable that goes back to index.php to just be used in the Google stuff.
So here you are:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google Charts -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
google.setOnLoadCallback(drawChart01);
// CHART 01
function drawChart01() {
var data = google.visualization.arrayToDataTable([
['Technological Area', 'Number of Publications'],
<?php echo $_SESSION['techAreas03']; ?>
]);
var options = {
chartArea: {width:'100%',height:'100%'},
forceIFrame: 'false',
is3D: 'true',
pieSliceText: 'value',
sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
titlePosition: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="publn-nr-srch" action="script.php" method="post" role="form">
<input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
<input id="btn-srch" type="submit" value="Search">
</form>
<?php
if(isset($_SESSION['techAreas03'])){
echo '<div id="tech-areas"></div>';
}
?>
</body>
</html>
and the script.php:
<?php
session_start();
# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
$techAreas00[] = ($r['techarea']);
}
# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));
# Count values.
$techAreas02 = array_count_values($techAreas01);
# Sort array.
arsort($techAreas02);
# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '[\''.$k.'\','. $v.']'; }, $techAreas02, array_keys($techAreas02)));
$_SESSION['techAreas03'] = $techAreas03;
# Reload index.php, but now with the variable $techAreas03 that will be used in the head to populate the GOOGLE CHART.
header(Location: index.php);
This work just fine.
Now when I try to use ajax to avoid that my index.php reloads I'm unable to plot the charts. The problem is that the Google script was already loaded before the script.php creates the variable. More about the problem in the original answer below.
And here are the codes of the modified pages:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google Charts -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
google.setOnLoadCallback(drawChart01);
// CHART 01
function drawChart01() {
var data = google.visualization.arrayToDataTable([
['Technological Area', 'Number of Publications'],
<?php echo $techAreas03; ?>
]);
var options = {
chartArea: {width:'100%',height:'100%'},
forceIFrame: 'false',
is3D: 'true',
pieSliceText: 'value',
sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
titlePosition: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="publn-nr-srch" action="" method="post" role="form">
<input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
<input id="btn-srch" type="submit" value="Search">
</form>
<div id="ajax"></div>
</body>
<script type="text/javascript">
$(function(){
$('form#publn-nr-srch').submit(function(){
$.ajax({
url: 'script.php',
type: 'POST',
data: $('form#publn-nr-srch').serialize(),
success: function(response) {
$('div#ajax').html(response);
}
});
return false;
});
});
</script>
</html>
and here the script.php:
<?php
session_start();
# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
$techAreas00[] = ($r['techarea']);
}
# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));
# Count values
$techAreas02 = array_count_values($techAreas01);
# Sort array.
arsort($techAreas02);
# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '[\''.$k.'\','. $v.']'; }, $techAreas02, array_keys($techAreas02)));
I my research about the issue I found many threads that talked about the call back function to plot the chart with ajax, but if we've already have the data that build the chart. The problem is that I didn't find any answer specific to my issue, because I have to send another data via ajax (namely the publication number = publn-in) the begins a query and the result of this query is the data that will be used by Google chart.
I hope I could be a little bit more intelligible now and that you guys can help me.
As already said, more info below and at any time you can ask more.
Many thanks!
EDIT END
ORIGINAL POST BEGIN
I have a form which I use to send info to a php script through ajax.
This script get this info, queries database and give me back an array which I transform in a string.
This string would be used to plot google chart.
I searched how I could plot the chart after a ajax call, but I was unable to get the expected results.
The problem is that the is already loaded and we have to use a callback to plot the chart.
Here my 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(drawChart04);
function drawChart04() {
var data = google.visualization.arrayToDataTable([
['Publication', 'Similarity'],
<?php echo $chart; ?>
]);
var options = {
chartArea: {width:'80%',height:'80%'},
forceIFrame: 'true',
titlePosition: 'none',
hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
legend: {position: 'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="publn-nr-srch" action="" method="post" role="form">
<input class="form-control" id="publn-in" name="publn-in" placeholder="Publication Number" type="text" value="" required />
<input id="btn-srch" class="btn btn-sm btn-primary" type="submit" value=" Search ">
</form>
<div id="ajax"></div>
</body>
<script type="text/javascript">
$(function(){
$('form#publn-nr-srch').submit(function(){
$.ajax({
url: '../models/pubSearchScr.php',
type: 'POST',
data: $('form#publn-nr-srch').serialize(),
success: function(response) {
$('div#ajax').html(response);
}
});
return false;
});
});
</script>
</html>
After the script runs I receive, for example, following string in a variable (here everything runs well):
$chart = "['1977',8], ['1978',31], ['1979',48], ['1980',34], ['1981',30], ['1982',37], ['1983',28], ['1984',31], ['1985',40], ['1986',32], ['1987',44], ['1988',42], ['1989',45], ['1990',43], ['1991',36], ['1992',31], ['1993',34], ['1994',26], ['1995',25], ['1996',41], ['1997',35], ['1998',27], ['1999',25], ['2000',14], ['2001',31], ['2002',19], ['2003',16], ['2004',21], ['2005',20], ['2006',12], ['2007',16], ['2008',29], ['2009',10], ['2010',13], ['2011',22], ['2012',2], ['2013',2]";
which I use in the google stuff (seen above into head session as well - ):
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart04);
function drawChart04() {
var data = google.visualization.arrayToDataTable([
['Publication', 'Similarity'],
<?php echo $chart; ?>
]);
var options = {
chartArea: {width:'80%',height:'80%'},
forceIFrame: 'true',
titlePosition: 'none',
hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
legend: {position: 'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
chart.draw(data, options);
}
</script>
In the script, as well I have following variable that is echoed in the ende. In the ende I can see the html stuff on screen, but not the chart:
$output = '
<!-- Similarity Curve -->
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">
<i class="fa fa-line-chart"></i>
Similarity Curve
</div>
</div>
<div class="panel-body">
<div id="sim-curve"></div>
</div>
</div>
</div>';
echo $output;
I understand the problem, that the head with google chart info is already loaded without the $chart variable before I run the ajax call. Then when I start it everything goes well, but the chart cannot be plotted. In my research I read about callback function, etc and I thought it was already in my code. If not, what exactely need in my case and WHERE? In head as well or in the middle of html code, or in the script?
One advice: When I do the same without ajax, namely using a html form that send info to the php script and the script is then redirect back to the file, everthing works fine, because the head is loaded once more with the entire page. My problem is when I have to use the amazing ajax.
Any help would be appreciate.
Many thanks in advance.
ORIGINAL POST END
Firstly, you should create a function that is used to draw the google chart with the data of chart is input.
Example: drawChart(inputData) = drawChart04(data);
Secondly, you create a variable that stores data of the chart:
//var inputData = your data;
var inputData = google.visualization.arrayToDataTable([
['Publication', 'Similarity'],
<?php echo $chart; ?>
]);
Thirdly, you have to know how to return data by using ajax on the server (PHP):
Example: dataChart = you query or to do something to get it;
echo json_encode(dataChart); exit; //This is just an example.
Fourthly, you have to know how to pass data from PHP to Javascript. I mean when you receive the response, you have to know how to build inputData base on the response.
$.ajax({url: "....php", type: "POST", dataType: "json", data:{..}})
.done(function(response){
inputData = response; //You have to convert response to inputData. Maybe Json.parse(response).
//I don't know, You have to know that you response. So find the best way to create inputData.
drawChart(inputData);//And finally call this function
});
That's it. I think that you can understand what I mentioned above. If you cannot fix this thing. Message me by my skype. I will fix it for you. SkypeID: jewelnguyen8

Categories