PHP variables in Javascript doesn't work - javascript

I am trying to show fetched data in Google charts, but PHP variables inside the javascript are not echoed.. If I echo variables outside of the javascript all works fine, so I suspect that something must be wrong in my javascript.. I double-checked everything but I can't figure our where is the issue..
The code does not show any errors!
This is the output in browser source..
['Active Posts',$post_counts],['Categories',$category_counts],['Users',$user_counts],['Comments',$comment_counts],
Any suggestion?
Thank you
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Data', 'Count'],
<?php
$data_text = ['Active Posts', 'Categories', 'Users', 'Comments'];
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];
for($i = 0; $i < 4; $i++) {
echo "['$data_text[$i]'" . "," . "$data_count[$i]],";
}
?>
]);
var options = {
chart: {
title: '',
subtitle: '',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>

Since you're already using PHP to output data for JS, you can just use json_encode to convert your ARRAY to JSON data.
<?php
$data = [
'Data' => 'Count',
'Active Posts' => $post_counts,
'Categories' => $category_counts,
'Users' => $user_counts,
'Comments' => $comment_counts
];
$json = json_encode($data);
?>
var data = google.visualization.arrayToDataTable("<?php echo $json; ?>");

Remove quotes from php variables,
Use this,
$data_count = [$post_counts, $category_counts, $user_counts, $comment_counts];
instead of,
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];

Related

How to create a dynamic number of datasets based on DB values

My goal is to render a graph in PHP using CanvasJS but with multiple datasets dynamically generated based on the values in a DB. Generating this graph with only 1 dataset was working just fine, making it "dynamic" seems to be a challenge.
For 1 dataset I used the code below:
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
Where $dataPoint is send to the JS code
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
type: "line",
dataPoints: <?php echo json_encode($dataPoint, JSON_NUMERIC_CHECK); ?>
}
]
});
chart.render();
});
</script>
So far, so good, so, next step is to extend this to multiple datasets. In this case, for each user in the view "completedgames" we will create a new dataset $datapoint and each $datapoint will be added to the overal dataset $datapoints as shown below:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($dataPoints, $dataPoint);
$dataPoint = array();
}
Where $dataPoints is the value now send to the same JS code as shown in above. Unfortunately this is where it goes wrong. data array_push() function doesn't feel right but I have no idea what the alternative is.
So, I hope this is sufficient information, all information is welcome and thanks in advance!
You have a few different problems, first when appending the data I would do this:
$dataPoint[] = array("x"=> $i , "y"=> $score);
Also I would get rid of this as it seems to be clearing out $dataPoint and might actually be creating additional levels in the array.
array_push($dataPoints, $dataPoint);
$dataPoint = array();
This code creates a $charts variable which looks like the data array in your javascript chart definition, rather than making a representation of just the dataPoints array. That should allow you to have as many data sets as you want.
$charts = [];
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$dataPoint = [];
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($charts, array(
"type" => "line",
"dataPoints" => $dataPoint
));
}
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: <?php echo json_encode($charts, JSON_NUMERIC_CHECK); ?>
});
chart.render();
});
</script>
Using James' input I was able to make my Graph with multiple lines. Just needed to reset the counter and $dataPoint array: here is the working code:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
json_encode($dataPoint, JSON_NUMERIC_CHECK);
$i++;
}
//array_push($dataPoints, $dataPoint);
// $dataPoint = array();
array_push($charts, array("type" => "line", "dataPoints" => $dataPoint));
$dataPoint = array();
$i = 0;
}
Thanks for all your inputs!

Cannot read property 'DataTable' of undefined in google charts

as the title saying im getting this error when trying to get charts inside function in another file like this
functions.php
function get_likes($catid){
require dirname (__FILE__).'/dbfunction.php';
?>
<script type="text/javascript" src="../assets/js/charts_min.js"></script>
<script type="text/javascript" src="../assets/js/functions.js"></script>
<?php
/// myquery here fetching the likes from database
?>
<script>
google.charts.load('current', {'packages':['corechart']});
</script>
<?php
if ($polls->execute()) {
while ($row = $polls->fetch(PDO::FETCH_ASSOC)) {
?>
<script>
a= <?php echo 2; ?> ;
b= <?php echo 3; ?> ;
c= <?php echo 5; ?> ;
i= <?php echo $row['id']; ?> ; ///// this i is looped to id 31 and 32
google.charts.setOnLoadCallback(function() { drawChart(a,b,c,i)}); ////But this didnt loop and it prints one chart for id 31. Because when i make alert(i) inside drawChart it alerts two times 31 and 31 .
</script>
<?php
echo "<div id="Votes_container"></div>";
}
}
my functions.js
function drawChart(a,b,c,i) {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['do', a],
['ri', b],
['me', c]
]);
// Set chart options
var options = {'title':'',
'width':500,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('Votes_container'+i));
chart.draw(data, options);
}
my index.php
require 'includes/functions.php';
$id = 1 ;
get_likes($catid) ;
So when i load index.php i want to get charts which gets data from database and come with get_likes() function , but my try didnt realise and it throws the error in the title .
where did the mistake located . Please ask me if i forget something before downvoting :) .
thanks for the help .
EDIT: i have edited the id of the divs where it should load the charts but it doesnt work either and same error.
Edited as the comment suggested and it prints the chart but its not looped now throw all ids.
Last Edit : this edit im writing how it worked for me.
I had to declare variables inside the function ,
google.charts.setOnLoadCallback(function() {
a= <?php echo 2; ?> ;
b= <?php echo 3; ?> ;
c= <?php echo 5; ?> ;
i= <?php echo $row['id']; ?> ;
drawChart(a,b,c,i)});

Get JSON Data from same file

i am trying to display google charts with data from a MYSQL database. It work's when i am using two seperate files (php/js) but i want to process the data in one file.
Heres what i got:
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Meter', 'type' => 'number')
);
$rows = array();
$select->execute();
while ($result = $select->fetch(PDO::FETCH_ASSOC)) {
$timestamp = strtotime($result['date']);
$date = date("d.m.Y - H:i", $timestamp);
$temp = array();
$temp[] = array('v' => $date);
$temp[] = array('v' => $result['meter']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$json = json_encode($table);
echo $json;
?>
<html>
<head>
<script type="text/javascript" src="../assets/js/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
dataType: "json",
async: true
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div2'));
chart.draw(data, {width: 1000, height: 240});
}
</script>
</head>
<body>
<hr class="major" />
<div id="chart_div2"></div>
</body>
</html>
The PHP data gets encoded properly but i dont know how to "send" the data to the javascript part. Is it possible to receive the JSON data in the same file?
When i change async: true to false, it just displays the code from the whole page, with true it displays undefined.
Kind regards,
Skar
when you echo the $json that way
<?php
// ...getting data
?>
<script>
var jsonData = <?php echo $json; ?>;
</script>
<?php
// rest of page...
you can use it in javascript later and don't need the ajax anymore.
//....
chart.draw(jsonData, {width: 1000, height: 240});
//....

Getting values from a PHP associative array using jQuery

I Have a html select element generated in PHP from an array as follows
$countries = array(
array('iso' => 'AF', 'name' => 'Afghanistan', 'key' => 'Red'),
array('iso' => 'AX', 'name' => 'Ă…land Islands','key' => 'Yellow'),
array('iso' => 'AL', 'name' => 'Albania', 'key' => 'Blue')
);
$select = '<select id="country_select" onchange="countryfind()">';
foreach($countries as $country) {
$select .= '<option value="'.$country['key'].'">'.$country['name'].'</option>';
}
$select = '</select>';
return $select;
The select box uses a small javascript function to displays the country key of the selected country:
function countryfind(){
jQuery('#countrykey').text(
jQuery('#country_select option:selected').val()
)};
I want to now use that key to interface with another PHP array which contain information about the country and display that country in the #countrykey div instead of the selected value:
$si_federations = array(
'Red' => array('name'=>'A Red Country', 'url'=>'http://www.redcountry.com'),
'Blue' => array('name'=>'A Blue Country', 'url'=>'http://www.soroptimisteurope.org'),
);
Is this something that can be easily achieved, or is my approach entirely wrong?
You're on the right track here. So, here's how to get this to do what you want
Within your <script> block we want to output that array in JSON
var federations = <?php echo json_encode($si_federations); ?>;
Now, when you run countryfind we want to pull the value out of that object and display it as well. So let's modify your function
function countryfind(){
var fed;
var selected = jQuery('#country_select option:selected').val();
if(federations[selected] !== undefined) fed = federations[selected];
else fed = {"name":"Default Name", "url":""}; //placeholders if it's not defined
jQuery('#countrykey').text(
selected + ' - ' + fed.name + ' ' + fed.url;
)};
I don't know how you want it displayed (I just dumped it as text for simplicity), but this gets you the data you need so you can take it from there
You have to convert your php associative array into js object for further reference. As php runs on server and you are doing every action on client side so right after page loads, your php is useless. You need js var so that you can reference it further.
Like this:
<script>
var countries = [];
var country = {};
<?php foreach($si_federations as $k => $country): ?>
<?php foreach($country as $key=>$val): ?>
country['<?php echo $key; ?>'] = '<?php echo $val; ?>';
<?php endforeach; ?>
countries['<?php echo $k; ?>'] = country;
<?php endforeach; ?>
function countryfind(){
var keyVal = jQuery('#country_select option:selected').val();
jQuery('#countrykey').text('name: '+countries[keyVal]['name']+' url: '+countries[keyVal]['url']);
}
</script>
I hope it helps

How to pass variables from while loop of PHP to JavaScript?

I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}

Categories

Resources