How to pass variables from while loop of PHP to JavaScript? - 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);
}

Related

PHP variables in Javascript doesn't work

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'];

How to insert a PHP 'while loop' into JavaScript code?

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>

passing array data from PHP to Javascript

I am fetching an array from a MySQL result into a array variable. I can successfully use a simple php echo line in the javascript beneath to grab the first $row element, but I want to use json_encode to get the whole array at once.
When I do this and try to set a javascript var to the first array element something goes wrong and even the single var method stops working.
<?php
.
.
.
while($row = $result->fetch_array(MYSQLI_NUM)) {
$row1 = $row[0];
}
?>
<script type="text/javascript">
var RowArray = <?php echo json_encode($row); ?>;
var RA1 = RowArray[0];
window.alert(RA1);
var Row1 = '<?php echo $row1; ?>';
window.alert(Row1);
</script>
Make an array containing all the records:
$rows = [];
while ($row = $result->fetch_array(MYSQLI_NUM))
{
// do custom modifications to $row if neededed
$rows[] = $row; // push to array
}
Or just:
$rows = $result->fetch_all(MYSQLI_NUM);
And then use json_encode() with $rows.

Getting my dynamic php array to js

Here's what I got
$x=$ris;
while ($x<$rie){
array_push($array, pg_fetch_result($result,$x,0));
$x=$x+1;
}
So I'm just pushing lot's of values from a column to $array. I want to transmit the data in this array to a js array. So here's what's happening:
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
while (temp2<temp)
{
jarray.push(<?php echo json_encode($array[temp2]); ?>);
temp2++;
}
console.log(jarray)
</script>
Whenever I try to print anything out, jarray has nothing in it, which leads me to think that this
jarray.push(<?php echo json_encode($array[temp2]); ?>);
line is messed up. It's probably because I'm trying to reference a js variable in a php echo. The problem is I'm trying to make a while loop to just copy the array over, but in js, I'm incrementing a js var, so how can I possibly do this?
Try my code. First json_encode your php array and then JSON.parse in js after that while loop.
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
var arr = '<?php echo json_encode($array); ?>';
var arr_p = JSON.parse(arr);
while (temp2<temp)
{
jarray.push(arr_p[temp2]);
temp2++;
}
console.log(jarray)
</script>

from mysql to javascript variable

Looking for a simple solution here, I have looked around but nothing seems to give me a simple solution. I want to get data FROM my mysql database and then into my javascript variables.
These two var items in my .js file named test.js and this file is called into my .html file.
var tag_name = 'example';
var client_id = '123456789';
In a .php file called call.php I use this method (PDO) to get the required data from MySQL:
$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name'];
$client_id = $row['client_id'];
}
I want to try and achieve something along the lines of this in the .js file test.js - this obviously wont work but hopefully sheds some light on what I am trying to achieve:
var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';
Can I do this using an Ajax method? In my research I read that I need to use JSON? If the question has been asked before, please direct me to a post that is not just someone dumping 50+ lines of code.
Here you go:
The javascript part:
$.ajax({
url: 'call.php',
dataType: 'json'
}).done(
function(data){
var tag_name = data[0];
var client_id = data[1];
}
);
The call.php file:
$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name'];
$client_id = $row['client_id'];
}
echo json_encode(array($tag_name,$client_id));
create a php script that will generate your js and instead of linking your script tag to the .js file link it to the php script that generates the js
PHP
<?php
//mysql stuff up here
header('Content-Type: text/javascript');
?>
//some js here
var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';
// some more js here
HTML
<script type="text/javascript" src="http://example.com/test.js.php"></script>
You can echo out your php variables as JSON and then consume them, but if you're just trying to set your js variables with data from php you might want to simply pass the variables in through a function call. Adding something like this to your php script to activate the Javascript you're trying to use for the page.
<script type="text/javascript">
setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>
and then creating that function in your .js file to utilize those values and do what you need.
function setVariables(name, id){
var tag_name = name
var client_id = id
//Operations that need these values.
}

Categories

Resources