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\": [";
}
Related
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);
}
});
});
im trying to populate a morris.js chart from a set of results. In my controller I create an array of the results and use json_encode to create a json array, here is the output in my view using print_r:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
How would I pass this to my morris.js chart to populate the chart using this data as label / value pairs? everything I try I get either a blank chart or an "undefined" variable or "NaN". Here is my controller:
function execute_search()
{
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Get results count and pass it as json:
$data = $this->search_model->count_res('$p_results_data');
$pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
foreach ($data as $item) {
if ($item['result'] === 'Positive') {
$pos++;
} elseif ($item['result'] === 'Negative') {
$neg++;
} elseif ($item['result'] === 'Pending') {
$pen++;
} elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
} else {
$misc++;
}
}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
$data = json_encode($res);
// Use the model to retrieve results:
$this->data['results'] = $this->search_model->get_results($search_term);
$this->data['chart'] = $data;
$this->data['totals'] = $this->search_model->total_res('$total_res');
// Pass the results to the view.
$this->data['subview'] = ('user/search_results');
$this->load->view('_layout_admin', $this->data);
}
and my morris.js:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
$results
],
});
Any help is greatly appreciated
Assuming that your morris.js is a normal javascript file, you cannot use php there by default: The server will not parse the .js file so the php source code will appear in your javascript.
You need to either:
Put the morris.js script contents in a php page in a javascript block so that the php gets parsed;
Make an ajax request from your morris.js script to get the data from the server in a separate request;
Set up your server to parse .js files as if they are / contain php.
The last one is just to illustrate what you would need, I would not recommend doing that.
In javascript, JSON.parse is your friend, assuming you have JSON that was created by PHP's json_encode function:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
JSON.parse( $results )
],
});
OR POSSIBLY
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( $results )
});
BUT THE WAY I DO IT
In the view:
<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />
In the JS (using jQuery):
var chartData = $('#chartData').val();
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( chartData )
});
After looking at the documentation for morris.js, I found that this is how you can do it the right way:
// Looking at the docs for morris.js:
// http://jsbin.com/ukaxod/144/embed?js,output
// This is your data, but it's all in one json object
var chartData = JSON.parse( $('#chartData').val() );
// We need to break up that object into parts of the donut
var donutParts = [];
$.each( chartData, function(k,v){
donutParts.push({
label: k,
value: v
});
});
// Now create the donut
Morris.Donut({
element: 'donutEg',
data: donutParts
});
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.
I am currently working in showing charts using php, html. I have been using a library fusionCharts.php which has been proved working before. However, right now, I have been getting error from the following line >
<?php
class FusionCharts {
private $constructorOptions = [];
private $constructorTemplate = <<<EOD
<script type="text/javascript">
FusionCharts.ready(function () {
new FusionCharts(__constructorOptions__);
});
</script>
EOD;
private $renderTemplate = <<<EOD
<script type='text/javascript'>
FusionCharts.ready(function () {
FusionCharts("__chartId__").render();
});
</script>
EOD;
But firebug shows that my error is being shown from another php funcion, graph.php. I have getting the error from the line 16 which is the line.
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="js/fusioncharts.js"></script>
</head>
<body>
And the error being thrown:
ReferenceError: FusionCharts is not defined
FusionCharts.ready(function () { graph.php (line 16, col 12)
ReferenceError: FusionCharts is not defined
FusionCharts.ready(function () {
I am adding all the files below:
fusioncharts.js
function fusioncharts_clickbar(){
var chartargs = '';
var chartid = arguments[0];
for (i=0; i<arguments.length; i++) {
chartargs = chartargs + arguments[i] + '/';
}
$.get(Drupal.settings.basePath +"/fusioncharts/data/"+ chartargs ,
function(data){
updateChartXML(chartid, data);
}
);
}
fusioncharts.php
<?php
class FusionCharts {
private $constructorOptions = [];
private $constructorTemplate = <<<EOD
<script type="text/javascript">
FusionCharts.ready(function () {
new FusionCharts(__constructorOptions__);
});
</script>
EOD;
private $renderTemplate = <<<EOD
<script type='text/javascript'>
FusionCharts.ready(function () {
FusionCharts("__chartId__").render();
});
</script>
EOD;
// constructor
function __construct($type, $id, $width = 400, $height = 300, $renderAt, $dataFormat, $dataSource) {
isset($type) ? $this->constructorOptions['type'] = $type : '';
isset($id) ? $this->constructorOptions['id'] = $id : 'php-fc-'.time();
isset($width) ? $this->constructorOptions['width'] = $width : '';
isset($height) ? $this->constructorOptions['height'] = $height : '';
isset($renderAt) ? $this->constructorOptions['renderAt'] = $renderAt : '';
isset($dataFormat) ? $this->constructorOptions['dataFormat'] = $dataFormat : '';
isset($dataSource) ? $this->constructorOptions['dataSource'] = $dataSource : '';
$tempArray = [];
foreach($this->constructorOptions as $key => $value) {
if ($key === 'dataSource') {
$tempArray['dataSource'] = '__dataSource__';
} else {
$tempArray[$key] = $value;
}
}
$jsonEncodedOptions = json_encode($tempArray);
if ($dataFormat === 'json') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xml') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', '\'__dataSource__\'', $jsonEncodedOptions);
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xmlurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'jsonurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
}
$newChartHTML = preg_replace('/__constructorOptions__/', $jsonEncodedOptions, $this->constructorTemplate);
echo $newChartHTML;
}
// render the chart created
// It prints a script and calls the FusionCharts javascript render method of created chart
function render() {
$renderHTML = preg_replace('/__chartId__/', $this->constructorOptions['id'], $this->renderTemplate);
echo $renderHTML;
}
}
?>
graph.php
<?php
require ("fusioncharts.php");
error_reporting(E_ERROR);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
$con=mysql_connect("localhost","root", "");
mysql_select_db("oligolilatest",$con);
?>
<html>
<head>
<title>Comparison of data with other</title>
<p> fdsfdsfds fsd f dsf sdf ds f</p>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="js/fusioncharts.js"></script>
</head>
<body>
<?php
$query = "SELECT UserID,FirstName FROM customerregistration ";
$result = mysql_query($query);
//echo "here1";
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
// echo "here11";
$arrData = array(
"chart" => array(
"caption" => "Number of User and Customer in the website",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysql_fetch_assoc($result)) {
array_push($arrData["data"], array(
"label" => $row["FirstName"],
"value" => $row["UserID"],
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
// echo "here3";
$jsonEncodedData = json_encode($arrData);
echo $jsonEncodedData;
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here-->
</div> </body></html>
Thank you.
Well you have given us quite some code to plow through; and it seems the fusioncharts.js you include in your <HEAD> (which you have also included in your post) simply doesn't include the FusionCharts class so there must be additional javascript files you need to include. Looking at their documentation you also need to include the library like this:
<script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>
Don't you include this library already in your other, working pages?
I'm having trouble parsing my php generated json array to a google chart. I have included Jquery, but some how i can't figure out how to parse my json data. I run a MySQL query to retrieve data from the database. Then i encode the query result with php json_encode.
I use ajax to get the json data from my php file.
getData.php:
<?php
function get_meta_values( $key, $type = 'workout', $status = 'publish' ) {
global $wpdb;
$user_ID = get_current_user_id();
if ( empty( $key ) )
return;
$r = $wpdb->get_results(
$wpdb->prepare( "
SELECT pm.meta_value, p.post_date FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
INNER JOIN $wpdb->term_relationships
ON (p.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy
ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE pm.meta_key = '%s'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id IN (4)
AND p.post_status = '%s'
AND p.post_type = '%s'
AND p.post_author = $user_ID
ORDER BY pm.meta_value DESC ",
$key,
$status,
$type));
if ( $r ) {
$user_ids = wp_list_pluck( $r, 'post_date' );
cache_users( $user_ids );
}
return $r;
}
$workout_history = get_meta_values( '1_rep', 'workout' );
echo json_encode($workout_history);
?>
The page that holds the chart:
<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 jsonData = $.ajax({
url: "http://localhost:41175/wp-content/themes/wordpress-bootstrap-master/getData.php",
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Test'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
When i try to echo my json file it looks like this:
[
{
"meta_value":"999",
"post_date":"2014-04-12 18:21:51"
},
{
"meta_value":"1",
"post_date":"2014-04-12 18:58:20"
}
]
Any suggestions to what i am doing wrong?
https://developers.google.com/chart/interactive/docs/reference#google.visualization.arraytodatatable
Seems that your JSON dataset is incorrect for use with that method. It should be (in javascript):
var data = [
['metavalue', 'post_date'],
['999', '2014-04-12 18:21:51'],
['1', '2014-04-12 18:58:20']
]
which in JSON equals to:
[["metavalue","post_date"],["999","2014-04-12 18:21:51"],["1","2014-04-12 18:58:20"]]
As I have no clue where $workout_history is coming from I can't help you out with how get to that.
Your object graph is incorrect before you return $r do this:
$results = array();
$result[] = array_values($r);
return $result;
alternatively you can build an your array of array like this:
$results = array();
$result[] = array($r['message_type'], $r['post_date']);
return $result;