AddRows receiving PHP Array - javascript

I'm strugling getting data from PHP into a graph. I have the following pieces of code on 1 php page. First the simple part:
$sql = "SELECT * FROM (SELECT timestamp, CurrentKelvin, TargetKelvin, WeatherTempKelvin FROM `rawdata` ORDER BY `rawdata`.`timestamp` DESC LIMIT 10) AS ttbl ORDER BY `timestamp` ASC;";
$results = mysqli_query($con,$sql);
$ChartData = array();
foreach($results as $result)
{
$ChartData[] = array( (int)$result['CurrentKelvin'],(int)$result['TargetKelvin']);
}
$ChartData = json_encode($ChartData);
Then the javascript part:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'CurrentKelvin');
data.addColumn('number', 'TargetKelvin');
alert( <?php echo json_encode($ChartData); ?>);
data.addRows( <?php echo json_encode($ChartData); ?> );
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
When i run the above the alert command shows the following output:
[[292,290],[292,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290]]
But the data.addRows line generates the following error:
Error: Argument given to addRows must be either a number or an array
Changing the data.addRows to something simple (and changing data.addColumn to string, with the same array construction, I do get a graph:
data.addRows([
['Ivan', 5],
['Igor', 7],
['Felix', 8],
['Bob', 4]
]);
I just can't figure out what is going wrong. Any help is appreciated.

Answer given by Dinesh worked:
var json_arr = <?php echo json_encode($ChartData); ?>;
data.addRows(JSON.parse(json_arr));

Related

Dynamic google line chart not showing up with php and Javascript

I am using google charts to display a line graph on my locally hosted web page. I am using mysqli to take the data from my phpmyadmin database then echoing this into the row spaces in the javascript.
This is the code within my html body:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
data.addRows([
<?php
$sql = "SELECT id_rides, speed, date_completed FROM rides_done WHERE (id_users = $_SESSION[id])";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)) {
$date = $row['date_completed'];
$speed = floatval($row['speed']);
echo "['".$date."', ".$speed."],";
}
?>
]);
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
The problem is that nothing is being displayed on the web page.
I know that the query works as I tried this on it's own outside of the javascript and this was output: results of sql query
Before I added the dynamic element of the chart it was working fine with just random lists of data.
I was expecting to see a line graph with 'Average Speed' on the y-axis and 'Ride date' on the x-axis with 7 datapoints but nothing was displayed.
It seems that js is particular about datatypes here so I'm wondering if it is something to do with either of the following lines - both of which I have been fiddling around with to no avail.
echo "['".$date."', ".$speed."],";
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
Thank you very much. All suggestions and ideas are very welcome. As is probably evident I am very new to Javascript so likely to be making some stupid mistakes.
A couple of things I would say: As you appear to wish to use a date within the dataTable perhaps setting that as a date type column would be better and casting the value from the db query as a date using new Date(str). I'd also suggest that you use json_encode once you have run the db query to create a JSON object rather than manually building a string as you do above - one downside to that approach is the trailing comma which might cause issues.
I rattle together a working demo using bogus data from my db to emulate what you were trying to do here. The SQL query uses aliases to take arbitrary data and name it as you do so the Javascript remains fairly much the same.
With the JSON data it is easy to iterate through the Object using Object.keys( json ).forEach() type structure ( I apologise if this is new to you )
<?php
#add a db connection
chdir('../../dbo');
require 'db-conn-details.php';
require 'mysqli-conn.php';
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//www.gstatic.com/charts/loader.js'></script>
<script></script>
<title>Google charts.....</title>
<style>
#chart_div{
width:800px;height:600px
}
</style>
</head>
<body>
<div id='chart_div'></div>
<script>
<?php
$sql = 'SELECT `speed`, `date_completed` FROM `rides_done` WHERE ( `id_users` = $_SESSION[id] )';
$sql = 'select `dr` as `speed`, date(`lasteditdate`) as `date_completed` from `testtable` limit 20'; # example sql...
$result = $link->query( $sql );
$json = json_encode( $result->fetch_all( MYSQLI_ASSOC ) );
printf('const json=%s;', $json );
?>
google.charts.load('current', { packages: ['corechart'] } );
google.charts.setOnLoadCallback( drawBasic );
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Speed');
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
data.addRow( [ new Date( obj.date_completed ), parseFloat( obj.speed ) ] );
})
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart( document.getElementById('chart_div') );
chart.draw( data, options );
}
</script>
</body>
</html>
The above yielded a chart like this:

How to populate google visualization data table from MySQL database with PHP?

```
<?php
// open database connection
$connection = mysqli_connect('localhost', '', '');
// sql query
$result = mysql_query($connection, "SELECET name, author, publisher, yearOfPublish, ISBN
FROM books");
if(!$connection) {
die("Connection failer: " . mysqli_connect_error());
}
echo "Connected Succes";
?>
// html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
// draw table function
function drawTable() {
var data = new google.visualization.DataTable();
// add columns
data.addColumn('string', 'Name');
data.addColumn('string', 'Author');
data.addColumn('string', 'Publisher');
data.addColumn('number', 'Year Of Publish');
data.addColumn('number', 'ISBN');
// add rows
data.addRows([
// retrieve data from database
]);
...
```
I have a database where I keep book information, and I am trying to retrieve those book information and put them into a google data table. I successfully opened connection with the database. However, I do not know how I am going to execute the query and get the data from the database.
function drawTable() {
var data = google.visualization.arrayToDataTable([
['Title', 'Author', 'Publisher', 'Year Of Publish', 'ISBN'],
<?php while ($row = mysqli_fetch_array($result)) {?>
['<?php echo $row['name']?>' , '<?php echo $row['author']?>', '<?php echo $row['publisher']?>', '<?php echo $row['yearOfPublish']?>', '<?php echo $row['ISBN']?>'],
<?php } ?>
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '50%', height: '50%'});
}
I found a solution

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)});

How to use javascript array elements in google.visualization graphs

I have the following bit of code that draws graphs, in a loop, using google.visualisation based on values from a SQL table which I store in 3 arrays(i.e. $TotalView, $TotalFemaleView and $TotalMaleView) in the PHP portion. I use json_encode(referred this link) so I can use these arrays in JavaScript. But I am unable to access the array elements to draw the graphs. I have tried displaying the values of the arrays and they are correct.
<?php
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "test";
$AdName=[];
$TotalView=[];
$TotalMaleView=[];
$TotalFemaleView=[];
$rowcount=0;
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$result=mysqli_query($con,"SELECT `Ad Name`,`Total View Count`, `Total Female Viewers`, `Total Male Viewers` FROM `addata` WHERE `Disp Id`=1");
$rowcount=mysqli_num_rows($result);
if(!$result) {
die('Could not get data: ' . mysql_error());
}
// output data of each row
for($x = 0; $x < $rowcount; $x++)
{
$row = $result->fetch_assoc();
$TotalView[$x]=$row["Total View Count"];
$TotalFemaleView[$x]=$row["Total Female Viewers"];
$TotalMaleView[$x]=$row["Total Male Viewers"];
$AdName[$x]=$row["Ad Name"];
}
$con->close();
?>
<html>
<body>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<ul id="stats"></ul>
<script type="text/javascript">
var array1 = <?php echo json_encode($TotalView);?>;
var array2 = <?php echo json_encode($TotalFemaleView);?>;
var array3 = <?php echo json_encode($TotalMaleView);?>;
var array4 = <?php echo json_encode($AdName);?>;
google.charts.load('current',
{ callback: function ()
{
for ( y = 0; y < <?php echo $rowcount ?>; y++)
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'list');
data.addColumn('number', 'Viewers');
data.addRows([
['TotalViewers',array1[y]],
['Female Viewers', array2[y]],
['Male Viewers', array3[y]]
]);
var options = {title:array4[y],width:400,height:300};
var container = document.getElementById('stats').appendChild(document.createElement('div'));
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, options);
}
},
packages: ['corechart']
});
</script>
</body>
</html>
Can anyone point me towards the right direction?
Based on the information in your comments and updated PHP code, it seems that your data returned from the database queries has numbers in the form of strings. Before using eval() or the Javascript Number object, if you looked in the browser console then you might have seen errors like this:
Uncaught Error: Type mismatch. Value 12 does not match type number in column index 1
There are multiple options to resolve this (without using eval()):
Type cast the values as an integer or float when adding to the output arrays in PHP
$TotalView[$x] = (float)$row["Total View Count"];
use the JSON_NUMERIC_CHECK flag with json_encode (see this answer for more info).
var array1 = <?php echo json_encode($TotalView, JSON_NUMERIC_CHECK );?>;
But beware there are drawbacks to using that constant (see this article for an example).
See this updated phpfiddle. As you can see, I created a class to simulate the database query (since I don't have a database connection in that sandbox) but allows to have the same array creation.
Please run that fiddle, and inspect the output in the browser console. Notice how the results of json_encode() produce valid arrays in Javascript, like:
var array1 = [12,10,6];
var array2 = [8,4,1];
var array3 = [4,6,5];
var array4 = ["Audi","BMW","Suzuki"];
Interestingly, the unordered list tag (i.e. <ul id="stats">), which is considered flow content, is added to the head tag in your sample code. The head tag only allows meta-data content. Move that unordered list tag to the body tag.
See the output demonstrated in the snippet below.
var array1 = [22, 16, 35, 11];
var array2 = [10, 3, 4, 9];
var array3 = [12, 13, 31, 2];
google.charts.load('current', {
callback: function() {
for (var y = 0; y < array1.length; y++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'list');
data.addColumn('number', 'Viewers');
data.addRows([
['TotalViewers', array1[y]],
['Female Viewers', array2[y]],
['Male Viewers', array3[y]]
]);
var options = {
title: 'Ad 1',
width: 400,
height: 300
};
var container = document.getElementById('stats').appendChild(document.createElement('div'));
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, options);
}
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<ul id="stats"></ul>
Okay, I solved it. Had to pass the arrays in the eval() function before using them in the google.visualization function.
google.charts.load('current',
{ callback: function ()
{
for ( y = 0; y < <?php echo $rowcount ?>; y++)
{
array1[y]=eval(array1[y]);
array2[y]=eval(array2[y]);
array3[y]=eval(array3[y]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'list');
data.addColumn('number', 'Viewers');
data.addRows([
['TotalViewers',array1[y]],
['Female Viewers', array2[y]],
['Male Viewers', array3[y]]
]);
var options = {title:array4[y],width:400,height:300};
var container = document.getElementById('stats').appendChild(document.createElement('div'));
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, options);
}
},
packages: ['corechart']
});
EDIT:
I found what was causing the problem and a better solution to the eval().
The json_encode was storing the elements as strings in the arrays(as you can see from my source here).
According to this, it is a PHP version specific problem and there are a couple of workarounds:
Adding the flag JSON_NUMERIC_CHECK to the json_encode function. So
in my case, it will be: var array1 = <?php echo json_encode($TotalView,JSON_NUMERIC_CHECK);?>. But this, according to some of the comments, is unreliable in certain cases.
Another solution is fixing it in the PHP section while reading the database elements from the database. $TotalView[$x]=(int)$row['Total View Count']. So
this stores the database element, Total View Count as an integer in
the TotalView array.

How to query to DB & plot the values on dashboard dynamically?

I'm very new to dashboard stuffs.Learning PHP & javascript. I'm trying to create a pie-chart with the help of already available google-chart. I could able to make it (Because, data is hard coded). I'm trying same to plot the pie-chart with dynamic values (querying to DB & plot the values on pie-chart). I'm trying to do it, but couldn't. Could you please help me to achieve this (MySQL, say 2 columns Name & Score).
Working code [For static data]:
<html>
<head>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
**var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);**
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>
I understand above highlighted part does the work of loading static data.
Tried embedding above script with db related PHP. Probably, i might be missing to call it in right way. Could you please help me to provide the missing interface. I'm very new to all these technologies.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbName = "test";
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM student";
$result = $conn->query($query);
$jsonArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['Name'];
$jsonArrayItem['value'] = $row['Scores'];
array_push($jsonArray, $jsonArrayItem);
}
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);
?>
Intoduction
Ok, if your code works correctly I suppose currently you have made a php script that spits out a JSON document in the format you need.
Now you need to actually load the data with javascript and feed it into the charting API.
So instead of feeding the hardcoded array at var data = google.visualization.arrayToDataTable you need to load it from the php script.
Have a look at the following links that solve this problem either with pure JS or with JQuery:
How to get JSON from URL in Javascript?
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Example with JQuery
Keep in mind calls are asynchronous so you need to have your charting logic triggered in ( or by ) the listener that handles the ajax call.
$.getJSON('http://localhost/myApp/myScript.php&callback', function(data) {
var data = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});

Categories

Resources