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

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

Related

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.

Generating a chart using JS libraries

The following set of codes are used to generate a chart using fusionchart javascript library!
This is the php script
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "chart";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "L12345d";
//name of the db under which the table is created
$dbName = "test";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT * FROM top_odi_wicket_takers";
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['player'];
$jsonArrayItem['value'] = $row['wickets'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
This is the json script
$(function() {
$.ajax({
url: 'http://localhost/GP/Charts/chart_data.php',
type: 'GET',
success: function(data) {
chartData = data;
var chartProperties = {
"caption": "Top 10 wicket takes ODI Cricket in 2015",
"xAxisName": "Player",
"yAxisName": "Wickets Taken",
"rotatevalues": "1",
"theme": "zune"
};
apiChart = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
"chart": chartProperties,
"data": chartData
}
});
apiChart.render();
}
});
});
The follwoing code gives the html code
<!DOCTYPE html>
<html>
<head>
<title>Fusion Charts Column 2D Sample</title>
</head>
<body>
<div id="chart-container">FusionCharts will render here</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/fusioncharts.js"></script>
<script src="js/fusioncharts.charts.js"></script>
<script src="js/themes/fusioncharts.theme.zune.js"></script>
<script src="js/app.js"></script>
</body>
</html>
According to the tutorial i followed it should generate the chart when the html code is executed! But when its executed no chart apperas but only a text stating
"FusionCharts will render here" appears how can i correct the code inorder to generate the chart? i followed this tutorial exaclty http://www.fusioncharts.com/dev/using-with-server-side-languages/tutorials/php-mysql-charts.html
I guess you have not installed the jquery properly. Click here to download jquery and copy that under the above created js folder.
require('http://localhost/GP/Charts/chart_data.php'')
should be
require('http://localhost/GP/Charts/chart_data.php')
i think u should keep all the script files inside the head tag so that they load before the dom(div) loads..give it a try

SELECT Count from mysql to Google Geo Chart

I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().

Table has no columns - Google Charts - PHP AJAX

I started to learn how to use Google Charts today and I'm a bit stuck.
I have dynamic data (changes about 3-4 times a day) to pump into the chart (Pie Chart). I'm using AJAX as the data source and PHP as my backend.. I tried to do it this way but to no avail:
AJAX:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';
$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");
$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_ASSOC);
if (!empty($MembershipTotals)) {
foreach ($MembershipTotals as $MembershipTotal) {
$data[] = array(
"cols" => array("id"=>"Membership_Level_Name", "label"=>"Membership Level", "type"=>"varchar"),
array("id"=>"MemTotal", "label"=>"Total", "pattern"=>"", "type"=>"number"),
"rows" => array($MembershipTotal['Membership_Level_Name'], $MembershipTotal['MemTotal'])
);
}
}
echo json_encode($data);
so thats my ajax, and it produces:
(ok wont let me post an image but heres the results)
[{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Start Up","24"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member","131"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member Plus","170"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Premier Member","31"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Bronze","97"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Silver","145"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Gold","188"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Affiliate","3"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Charity\/Education","4"]}]
So the next step is to call that data, I took the code from Google Charts "Connecting to a database" (or something like that) page:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/ajax/charts/membershiptotals.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
Reload the web page and it produces the error:
Table has no columns
I don't understand why though.. I looked at other solutions and posted on Quora and the Google group for the API but to no avail.. could someone tell me whats wrong with the code??
I found the answer:
AJAX was changed to:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';
$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");
$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_OBJ);
$col1=array();
$col1["id"]="";
$col1["label"]="Membership Type";
$col1["pattern"]="";
$col1["type"]="string";
$col2=array();
$col2["id"]="";
$col2["label"]="Total";
$col2["pattern"]="";
$col2["type"]="number";
$cols = array($col1,$col2);
$rows=array();
foreach ($MembershipTotals AS $MembershipTotal) { //foreach ($Event->TrainingTotals['ConfirmedTotal'] AS $Key => $Value) {
$cell0["v"]=$MembershipTotal->Membership_Level_Name;
$cell1["v"]=intval($MembershipTotal->MemTotal);
$row0["c"]=array($cell0,$cell1);
array_push($rows, $row0);
}
$data=array("cols"=>$cols,"rows"=>$rows);
echo json_encode($data);
which made it a bit easier and then on the actual page:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/ajax/charts/membershiptotals.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {title:'Membership Bookings', width: 800, height: 500});
}
</script>
Basically I had to clearly declare the columns, and the intval is to turn it into a integer, otherwise it returns the number as a string which Google doesn't like.. hope this helps anyone :)
thanks to Harish for an answer but I needed it more dynamic :-)
this is the format of the array to be passed.
javascript:
var jsondata; //json data recived from php script
var data = google.visualization.arrayToDataTable(jsondata);
php:
$data = array(
array('Membership Level', 'MemTotal'),
array('Member Plus', 170),
array('Member', 131)
);
echo json_encode($data);
Your have to pass Json array not object.

AddRows receiving PHP Array

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

Categories

Resources