Parsing JSON array into Google Charts DataTable - javascript
I've done quite a bit of searching and have found solutions for issues similar to my problem but nothing that has worked so far. Any help is appreciated.
I am attempting to create a Google Line Chart from data I am querying from my database and then parsing to JSON. My query and JSON looks good but when I insert it into the DataTable the web page is blank.
This the JSON output I have:
[["date","percentage"],["0000-00-00 00:00:00",28.18],["2015-01-06 06:00:01",93.65],["2015-01-07 06:00:01",85.9],["2015-01-08 06:08:43",89.25],["2015-01-09 06:08:42",99.26],["2015-01-10 14:50:37",99.48],["2015-02-06 06:00:01",93.88],["2015-02-07 06:00:01",89.15],["2015-02-08 06:08:51",89.55],["2015-02-09 06:09:25",98.94],["2015-02-09 17:26:50",98.94],["2015-02-10 06:10:55",99.06],["2015-03-07 06:11:32",85.7],["2015-03-08 06:07:58",89.86],["2015-03-10 06:11:04",99.06],["2015-04-06 14:19:26",82.17],["2015-04-07 06:11:47",85.8],["2015-04-08 06:10:01",89.76],["2015-04-10 06:10:53",100],["2015-05-06 16:25:01",91.21],["2015-05-07 06:11:12",85.7],["2015-05-08 06:08:53",89.25],["2015-05-09 22:35:40",97.77],["2015-05-10 06:10:39",99.17],["2015-05-10 21:28:01",98.85],["2015-06-06 06:00:02",90.84],["2015-06-07 06:11:05",85.9],["2015-06-09 06:09:32",97.88],["2015-06-10 06:10:55",99.79],["2015-07-06 06:00:01",91.33],["2015-07-07 06:10:35",85.09],["2015-07-08 06:09:36",89.45],["2015-07-09 06:08:55",98.2],["2015-07-10 06:12:44",5.94],["2015-08-06 06:00:01",91.58],["2015-08-08 06:09:03",89.05],["2015-08-09 06:09:23",97.03],["2015-08-09 15:54:27",97.67],["2015-09-06 06:00:01",90.96],["2015-09-07 06:12:33",84.99],["2015-09-08 06:08:54",89.15],["2015-09-09 06:12:48",99.26],["2015-09-09 14:29:39",95.02],["2015-10-06 06:00:01",91.09],["2015-10-07 06:13:13",89.35],["2015-10-08 06:08:42",89.25],["2015-10-09 06:09:40",99.47],["2015-10-09 17:14:20",99.47],["2015-11-05 06:00:01",97.41],["2015-11-06 06:00:01",85.47],["2015-11-07 06:12:17",89.45],["2015-11-08 06:10:45",89.45],["2015-12-05 06:00:01",96.7],["2015-12-06 06:00:01",90.72],["2015-12-07 06:12:22",88.74],["2015-12-09 06:09:39",99.58]]
When I insert this into the JSON Validator at https://jsonformatter.curiousconcept.com it says it is valid JSON and when I hard code it in everything seems to work..
Here is my code:
<?php
$dbhost="localhost";
$dblogin="root";
$dbpwd="password!";
$dbname="qaDB";
$db = mysql_connect($dbhost,$dblogin,$dbpwd);
mysql_select_db($dbname);
$SQLString = "SELECT date, percentage FROM reports WHERE RTYPE_ID=1";
$result = mysql_query($SQLString);
$num = mysql_num_rows($result);
# set heading
$data[0] = array('date','percentage');
for ($i=1; $i<($num+1); $i++)
{
$data[$i] = array(substr(mysql_result($result, $i-1, "date"), 0, 20),
(float) mysql_result($result, $i-1, "percentage"));
}
echo json_encode($data);
mysql_close($db);
?>
Here is the page to create the Google line chart.
<html>
<head>
<title>JSON Chart Test</title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
// var newWin = window.open();
var jsonData = $.ajax({
url: "legacyDashboardJSON.php",
dataType: "json",
async: false
}).responseText;
//var newStr = jsonData.substring(1, jsonData .length-1);
//newWin.document.write(jsonData);
// var parsedData = JSON.parse(newStr);
//var obj = JSON.stringify(newStr);
var data = google.visualization.DataTable(jsonData);
var options = {
title: 'Stats'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div">
</div>
</body>
</html>
Thanks!
UPDATE Found the solution.
Here's the code:
<?php
$DB_NAME = 'qaDB';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '!';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query('SELECT date,percentage FROM reports');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'date', 'type' => 'string'),
array('label' => 'percentage', 'type' => 'number')
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['date']);
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
mysql_close($mysqli);
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></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: "legacyDashboardJSON.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 options = {
title: 'Metrics',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
You need to provide a success function in your .ajax call that will execute when the data returns. Anything that needs the data should be placed inside this function, or passed from within the success function to another function. You could also use .done() on the end of your .ajax call and place the rest of your script in there.
Related
I've used this xmlhttprequest approach to be able to make a real-time gauge chart that shows water quality but not working?
Without this xmlhttprequest, the gauge chart is working fine and showing up like here But after I add this code in index.php, the chart suddenly stop showing up which happens when there is something wrong (even if there is no error that is being detected) but I can't find out where... Index.php Code for automatically updating/ refreshing the gauge chart data with interval without reloading the page. <?php include("connection.php"); ?> <html> <head> <title> </title> </head> <body> <div class="container"> <div id="link_wrapper"> </div> </div> </body> </html> <script> function loadXMLDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("link_wrapper").innerHTML = this.responseText; } }; xhttp.open("GET", "server.php", true); xhttp.send(); } setInterval(function(){ loadXMLDoc(); // 1sec },1000); window.onload = loadXMLDoc; </script> Server.php Code for the dynamic gauge chart <?php $connection = mysqli_connect('localhost', 'root', '', 'adminpanel'); $query = 'SELECT * FROM tbl_waterquality ORDER BY id DESC'; $query_run = mysqli_query($connection, $query); while ($row = mysqli_fetch_array($query_run)) { ?> <html> <head> <div class="justify-content-between"> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', { 'packages': ['gauge'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Label', 'Value'], ['Temperature', <?php echo $row['temperature'] ?>], ['pH', <?php echo $row['pH'] ?>], ['DO', <?php echo $row['DO'] ?>], ['Turbidity ', <?php echo $row['Turbidity'] ?>] ]); <?php } ?> var options = { width: 500, height: 200, minorTicks: 5, }; var chart = new google.visualization.Gauge(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <div id="chart_div" style="width: 400px; height: 120px,; margin-top:30px"></div> </body> </html>
The way to do this properly is to only use the PHP to get the DATA and then run it in the page. Return JSON from your database and pass it to the function that executes the visualization. This is your NEW server.php - it is complete <?php header("content-type: application/json"); $connection = mysqli_connect('localhost', 'root', '', 'adminpanel'); $query = 'SELECT * FROM tbl_waterquality ORDER BY id DESC'; $query_run = mysqli_query($connection, $query); $row = mysqli_fetch_array($query_run); // assuming ONE result echo <<<EOT [ ["Label", "Value"], ["Temperature", $row["temperature"]], ["pH", $row["pH"] ], ["DO", $row["DO"] ], ["Turbidity", $row["Turbidity"]] ] EOT ?> and use this page to call it Uncomment the commented fetch after testing <!doctype html> <html> <head> <meta charset="utf8" /> <title>Gauge</title> <script src="https://www.gstatic.com/charts/loader.js"></script> <script> /* ------------- Remove when you uncomment the fetch -----------*/ let temp = 25; // testdata const arr = [ ['Label', 'Value'], ['Temperature', temp], ['pH', 7.2], ['DO', 60], ['Turbidity ', 10] ]; // testdata /* ------------- END Remove -----------*/ let chart; const options = { width: 500, height: 200, minorTicks: 5, }; const drawChart = arr => { if (!chart) chart = new google.visualization.Gauge(document.getElementById('chart_div')); // only do this once var data = google.visualization.arrayToDataTable(arr); chart.draw(data, options); } const getData = () => { /* UNCOMMENT after test fetch('server.php') .then(response => response.json()) .then(arr => { drawChart(arr); setTimeout(getData, 2000); // run again }); */ /* REMOVE AFTER TEST */ drawChart(arr); // remove after test arr[1][1] = ++temp setTimeout(getData, 5000); // run again - remove after test /* END REMOVE */ }; window.addEventListener("load", () => { // when page loads google.charts.load('current', { 'packages': ['gauge'] }); google.charts.setOnLoadCallback(getData); // start }) </script> </head> <body> <div class="justify-content-between"> <div id="chart_div" style="width: 400px; height: 120px,; margin-top:30px"></div> </div> </body> </html> If you need to create an array of all rows, here is how to loop http://sandbox.onlinephpfunctions.com/code/8c371c0da3a5e7a91bcf8cf1e961f822c0755e57 $arr = array(array( "Label", "Value")); while ($row = mysqli_fetch_array($query_run)) { array_push($arr, array("Temperature", $row["temperature"]), array("pH", $row["pH"] ), array("DO", $row["DO"] ), array("Turbidity", $row["Turbidity"]) ); } echo json_encode($arr)
Draw Line Chart (chart data is coming from mysql) based upon selected date from datepicker (Date is coming from mysql table)
What i have trying to do draw a line chart based on date and Id mentioned in the date picker like this Below is My Code which i am currently using to populate the line chart HTML CODE (TO show the chart ) <html> <head> <title>Temperature chart</title> </head> <body> <div id="chart-container"> <canvas id="mycanvas"></canvas> </div> <script type="text/javascript" src="js/jquery-3.4.0.min.js"></script> <script type="text/javascript" src="js/Chart.min.js"></script> <script type="text/javascript" src="js/app.js"></script> </body> </html> data.php (using this file to get the data from mysql and printing it using json) <?php //setting header to json header('Content-Type: application/json'); header('Access-Control-Allow-Origin: http://localhost:8080/hurry/data.php', false); //database define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'canvasjs_db'); //get connection $mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if(!$mysqli){ die("Connection failed: " . $mysqli->error); } //query to get data from the table $query = sprintf("SELECT `temp`, `formatedate` FROM `datapoints` WHERE `device_id` = '50' AND `formatedate` >= '2019-04-02 09:26:00' AND `formatedate` <= '2019-04-03 13:26:00'"); //execute query $result = $mysqli->query($query); //loop through the returned data $data = array(); foreach ($result as $row) { $data[] = $row; } //free memory associated with result $result->close(); //close connection $mysqli->close(); //now print the data print json_encode($data); ?> app.js (using this file to populate the data in chart) $(document).ready(function(){ $.ajax({ url: "http://localhost:8080/Notifications/NewNotification/data.php", method: "GET", success: function(data) { console.log(data); var player = []; var score = []; for(var i in data) { player.push(data[i].formatedate); score.push(data[i].temp); } var chartdata = { labels: player, datasets : [ { label: 'Temperature ', hoverBackgroundColor: 'rgba(30, 0, 200)', hoverBorderColor: 'rgba(200, 200, 197)', data: score } ] }; var ctx = $("#mycanvas"); var lineGraph = new Chart(ctx, { type: 'line', data: chartdata }); }, error: function(data) { console.log(data); } }); });
PHP/JS - Google Graph - Echoing data out
I've looked at other questions similar to what I am asking however they are not what I need/trying to substitute the answer into my code. <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Stock Price', 'Date'], //['2014', 3000], <?php $DataSearchSQL = "SELECT * FROM stocklog WHERE status = 1 ORDER BY ID DESC LIMIT 7"; $DataSearchResult = mysqli_query($dbconfig,$DataSearchSQL); while($DataSearchRow=mysqli_fetch_array($DataSearchResult,MYSQLI_ASSOC)) { $data = $DataSearchRow["StockPrice"]; $timestamp = $DataSearchRow["Time"]; $splitTimeStamp = explode(" ",$timestamp); $date = $splitTimeStamp[0]; $info = "['{$date}', {$data}]"; echo json_encode($info); } ?> ]); I believe I am messing something up with $info and json_encode however I am not sure what to do, help is much appreciated.
Google charts / Use PHP to collect data from MySQL db
All, I am trying to use Google Charts (line chart) and retrieve the information from a MySQL db.Following steps 1> Collect data from MySQL db and encode output in JSON format(PHP) 2> Use HTML file to use Google charts (php is called from this HTML file) However somehow it is not working (screen stays blank) - hope somebody can help. Chrs, Jerome getData.php (yes I now I need to use MySQLI instead of these old commands .. :-)) <?php //Sample Database Connection Syntax for PHP and MySQL. //Connect To Database $hostname="localhost"; $username="xxxxxxx"; $password="xxxxxxx"; $dbname="xxxxxxxx"; $usertable="xxxxxxxxxx"; $yourfield0 = "FC"; $yourfield1 = "devInfo1"; $yourfield2 = "devInfo2"; $yourfield3 = "srvTime"; $con = mysql_connect($hostname,$username, $password); if (!$con) { die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>"); } mysql_select_db($dbname); # Check If Record Exists $query = "SELECT $yourfield0, $yourfield1, $yourfield2, $yourfield2 FROM $usertable ORDER BY Sensor.srvTime ASC"; $result = mysql_query($query); // ******* $table = array(); $table['cols'] = array( //Labels for the chart, these represent the column titles // array('id' => '', 'label' => 'FrameCount', 'type' => 'string'), // array('id' => '', 'label' => 'Temperature', 'type' => 'number') array('type' => 'string'), array('type' => 'number') ); // ***************** if($result) { while($row = mysql_fetch_array($result)) { $temp = array(); //Values $temp[] = array('v' => (string) $row[$yourfield0]); $temp[] = array('v' => (float) $row[$yourfield1]); $rows[] = array('c' => $temp); } } $table['rows'] = $rows; $jsonTable = json_encode($table); echo $jsonTable; //close the db connection & clean result mysql_close($con); mysql_free_result($result); return $jsonTable; ?> JSON OUTPUT (from above PHP) {"cols":[{"type":"string"},{"type":"number"}],"rows":[{"c":[{"v":"8058"},{"v":26.4}]},{"c":[{"v":"8081"},{"v":26.5}]},{"c":[{"v":"8091"},{"v":26.5}]},{"c":[{"v":"8092"},{"v":26.5}]},{"c":[{"v":"8094"},{"v":26.5}]},{"c":[{"v":"8096"},{"v":26.5}]}]} Google Line Charts <html> <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load the Visualization API and the corechart package. 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. Here it is retrieved from the getData.php // getData.php returns the data and it is storedx in jsonData. var jsonData = $.ajax({ url: "getData.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 options = { title: 'Sensor Information', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <div id="curve_chart" style="width: 900px; height: 500px"></div> </body> </html>
Google Charts not displaying values correctly
I'm having trouble displaying Google Charts correctly. I'm trying to do this with Ajax and PHP. This is the code that is loaded on the page: <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type='text/javascript'> // Dummy Array for now <?php $php_array = array( array('Terms', 'Visits'), array('test', 25), array('joke', 25), array('funny', 50), ); //Convert the PHP Array into a Javascript Array $js_array = json_encode($php_array); echo "var arrTableData = ". $js_array . ";\n"; ?> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawCharts); function drawCharts(){ // Each chart function $.getJSON('charts_ajax.php',{'a' : 'terms', 'd' : arrTableData }, function(data){ if(data){ initGoogleChart(data) }else { console.log("There is no data coming back"); } }); } function initGoogleChart(data){ var tableData = google.visualization.arrayToDataTable(data); var options = { title: 'Title' }; var chart = new google.visualization.PieChart(document.getElementById('terms-table')); chart.draw(tableData, options); } </script> and on the charts_ajax.php file there is this data: <?php if ($_GET['a'] == "terms") { $arrTableData = $_GET['d']; echo json_encode($arrTableData); } ?> This is what the Chart is outputting: Can anybody shed some light on this and possible help me fix it please?
Have you tried converting the data into a Google Charts JSON format? Here's an example. foreach($arrTableData as $r2) { if(!isset($google_JSON2)) { $google_JSON2 = "{\"cols\": ["; $column = array_keys($r2); foreach($column as $key=>$value) { $google_JSON_cols2[]="{\"id\": ".$key.", \"label\": \"".$value."\", \"type\": \"string\"}"; } $google_JSON2 .= implode(",",$google_JSON_cols2)."],\"rows\": ["; }