highcharts does not seem to be rendering - php

I am following this example
https://www.highcharts.com/docs/chart-and-series-types/pie-chart
I want to display highcharts through retrieving data from the database. My pie highcharts is not displaying though I am not getting any error. I am retrieving data from database mysql. here is my code
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'diseas Per area'
},
// tooltip: {
// formatter: function() {
// return '<b>' + this.point.name + '</b>: ' + this.y+ 'd Count';
// }
// },
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y;
}
},
showInLegend: true
}
},
series: []
};
$.getJSON("fcount.php", function(json) {
options.series = json;
chart = new Highcharts.Chart(options);
});
});
<div id="container2" style="height: 550px; min-width: 310px; max-width:800px; margin: 0 auto"></div>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
kindly tell me what I am doing wrong. It does not show any error but still it does not display
my php code is
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysql_query("SELECT `Area` AS Zone, COUNT( `Diease` ) AS problem FROM table GROUP BY `Area` ");
//$rows = array();
$rows['type'] = 'pie';
$rows['name'] = 'Diease Count';
//$rows['innerSize'] = '50%';
while ($r = mysql_fetch_array($result)) {
$rows['data'][] = array('zone '.$r['area'].'"', $r['problem']);
}
$rslt = array();
array_push($rslt,$rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
mysql_close($con);

instead of push array into an empty array like this
$rslt = array();
array_push($rslt,$rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
use it like below
echo json_encode($rows);

The lack of data is probably caused by the format of your options.series. When using a pie chart, your series should be formatted like this:
options.series = [{ name: 'Browsers',
data: [ ["Firefox",60] , ["Chrome",40]]
}]
In this JSFiddle I used your options code to generate the chart. So if your options.series looks like shown above, the chart should work.

Related

set dynamic graph in area chart

I am making one area graph dynamically in that I want to set the Data array dynamically. I have created variable and assign it Scores which example I have given below
$dataPoints = '30, 10, 40, 20, 30, 10, 50, 30, 30, 30, 40';
var dataPoints1 = '<?php echo $dataPoints; ?>';
var areaChart = c3.generate({
bindto: '#area-chart',
data: {
columns: [
['Score', dataPoints1]
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
But this Script is not working and it does not show a graph and if I set this value statically so it is working fine.
So can anybody help me with this...
Instead of fetching php string into js variable, pass php string directly to column, it will work
var areaChart = c3.generate({
bindto: '#area-chart',
data: {
columns: [
['Score', <?php echo $dataPoints; ?>] // use php variable directly
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
There is no need of dataPoints1 js variable.
EDIT
In that case,
In php I suppose ajax,
$dataPoints["Score"] = [30, 10, 40, 20, 30, 10, 50, 30, 30, 30, 40];
echo json_encode($dataPoints); die;
In JS
var chart = c3.generate({
bindto: '#area-chart',
data: {
url: 'your url to fetch above data',
mimeType: 'json',
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid: {
focus: {
show: false
}
}
});
This should solve your problem
I use your code as example and try to modify code with my database connection and sample table data.
Please try this, hope this will useful to you.
File (PHP + HTML + jQuery)
<?php
$servername = "localhost"; // Change with your server name
$username = "root"; // Change with your user name
$password = ""; // // Change with your password
$dbname = "test"; // // Change with your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT data FROM users"; // // Change with your table name
$result = $conn->query($sql);
$dataPoints = '';
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dataPoints .= $row['data'];
$dataPoints .= ',';
}
rtrim($dataPoints);
echo $dataPoints;
} else {
echo "0 results";
}
$conn->close();
?>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>C3.js</title>
<style type="text/css">
body{
text-align: center;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Graphs made easy</h1>
<div id="chart"></div>
</div>
<script type="text/javascript">
var dataPoints1 = ["Score", <?php echo $dataPoints;?>];
console.log('dataPoints : ', <?php echo $dataPoints;?>);
console.log('data2 : ', dataPoints1);
var areaChart = c3.generate({
bindto: '#chart',
data: {
columns: [
dataPoints1
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
</script>
</body>
</html>
Output

how to create proper json data format from mysql for highcharts

I have a json data that will retrive the selected data from database based on user checked on checkboxes. but I know my json data is not correct. Tried many way, but still wont works. This is the code:
<?php
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series1['name'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$jsonTable = json_encode($series1, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
Based from the code below, lets say if I checked 3 checkbox (BAT123, BIO222, HIS TEST),The json output will be like this:
{"name":["BAT123"],"data":[3.03]}
{"name":["BAT123","BIO222"],"data":[3.03,1.05]}
{"name":["BAT123","BIO222","his test"],"data":[3.03,1.05,3.03]}
I know the json above was wrong, So how to make the json data will be display like this:
[
{"name":["BAT123"],"data":[3.03]},
{"name":["BIO222"],"data":[1.05]},
{"name":["his test"],"data":[3.03]}
]
This is my highcharts javascript code:
<script type="text/javascript">
$(function () {
var data = [
<?php echo $jsonTable; ?>
];
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'SamHistogramDiv',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'SAM Histogram Results',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Percentage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: data[0]
});
});
});
Thank u very much for your time..
Problem was with the json data format. It should be like
var data = [{name:"BAT123",data:[3.03]},{name:"BIO222",data:[1.05]},{name:"his test",data:[3.03]}];
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>array($r['result']));
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
Pls check if you are getting the json string as mentioned above /* data */
Check this link
http://jsfiddle.net/highcharts/Sq3KL/2/
Try this
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>$r['result']);
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
the out put will be like
[{"name":"BAT123","data":"3.03"},{"name":"BIO222","data":"1.05"},{"name":"HIs test","data":"1.00"}]

Highcharts Display values from sql via json

Hello I try to use Highcharts with data's from an sql Database by using json.
There are all doing but I can't see any values
I get the Data's with this script:
<?php
header('content-type: text/html; charset=utf-8');
include("db.inc.php");
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWOR
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $con);
$sth0 = mysql_query("SELECT `DATETIME` FROM `dg_wall24` WHERE DATETIME >
NOW()INTERVAL 1 HOUR");
$rows0 = array();
$rows0['name'] = 'DATETIME';
while($r0 = mysql_fetch_array($sth0)) {
$rows0['data'][] = $r0['DATETIME'];
}
$sth1 = mysql_query("SELECT `dg_t01` FROM `dg_wall24` WHERE DATETIME >
NOW()INTERVAL 1 HOUR");
$rows1 = array();
$rows1['name'] = 'dg_t01';
while($r1 = mysql_fetch_array($sth1)) {
$rows1['data'][] = $r1['dg_t01'];
}
$sth2 = mysql_query("SELECT `dg_h01` FROM `dg_wall24` WHERE DATETIME >
NOW() INTERVAL 1 HOUR");
$rows2 = array();
$rows2['name'] = 'dg_h01';
while($r2 = mysql_fetch_array($sth2)) {
$rows2['data'][] = $r2['dg_h01'];
}
$result = array();
array_push($result,$rows0);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result);
mysql_close($con);
?>
The Result:
[{"name":"DATETIME","data":["2013-04-27 08:17:52","2013-04-27 08:22:52","2013-04-27 08:27:53","2013-04-27 08:32:54","2013-04-27 08:37:55","2013-04-27 08:42:55","2013-04-27 08:47:56","2013-04-27 08:52:57","2013-04-27 08:57:58","2013-04-27 09:02:58","2013-04-27 09:07:59","2013-04-27 09:13:00"]},{"name":"dg_t01","data":["22.40","22.40","22.40","22.40","22.30","22.30","22.40","22.40","22.40","22.40","22.40","22.40"]},{"name":"dg_h01","data":["40.20","40.40","40.50","40.80","40.70","40.70","40.80","40.90","41.00","41.00","40.90","40.70"]}]
In the Highchart I can See the timeline on the x Axis and the name of the values but no line and no values.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 40
},
title: {
text: 'Dachgeschoss',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
//categories: []
},
yAxis: {
title: {
text: 'Temperatur & Luftfeuchtigkeit'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("data2.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<script type="text/javascript" src="js/themes/gray.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
It is possible that I have an problem with the Dataformat (float, int...) or with the Point in the values?
Many thanks for the help
The problem is indeed that your JSON object contains String values instead of Float values for your data:
{ ... "data":["40.20","40.40","40.50", ... ]}
I don't know what the field type in your database is, and I'm no PHP coder, but you could try setting the JSON_NUMERIC_CHECK option on json_encode.
If that doesn't work for you, you could also convert the Strings using parseFloat in Javascript:
for (var i = 0, num; num = json[1].data[i]; i++)
{
json[1].data[i] = parseFloat(num);
}
See my example on Fiddle.

Jquery flot pie with PHP MYSQL

I have some problems. Excuse me for my english.
I'ld display the datas but nothing !!
I dont know where is the probleme. I dont find it.
Thnaks you for your help.
code html
<div id="pie2" style="height:300px"></div>
code javascript
jQuery(document).ready(function ($){
var options = {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 2 / 3,
tilt:0.5,
formatter: function(label, series)
{
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '% (' + series.data[0][1] + ')</div>';
},
background:
{
opacity: 0.8
}
}
}
},
legend: {
show: true
}
};
var dataset1 = <?php echo json_encode($pie);?>;
var data = [
{
"label": "Random Values",
"data": dataset1
}
];
var plotarea = $("#pie2");
$.plot( plotarea , data);
});
code PHP (source_pie.php)
$sql = "SELECT COUNT(rne) AS rne, dept FROM anuetab GROUP BY dept";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($sql)){
$pie[] = array(
'label'=>$row['dept'],
'data'=>$row['rne']
);
echo '<pre>';
print_r($pie);
echo '</pre>';
}
echo json_encode($pie);
try with mysql_fetch_row instead of mysql_fetch_assoc

Highcharts: Force show xAxis with datetime

My highcharts chart is showing like this now:
http://img90.imageshack.us/img90/3892/chart1p.png
But I need it to look like this:
http://img545.imageshack.us/img545/1333/chart2p.png
Currently its not showing empty values by hours.
My code:
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function () {
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: 'Earnings Today',
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000,
tickWidth: 0,
labels: {
align: 'center',
formatter: function () {
return Highcharts.dateFormat('%l%p', this.value);
}
},
},
yAxis: {
title: {
text: 'Earnings'
},
min: 0,
tickInterval: 2,
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
formatter: function () {
return '$' + this.y;
}
},
series: [{
name: 'Earnings Today, USD'
}
]
}
jQuery.get('data_today.php', null, function (tsv) {
var lines = [];
earnings = [];
try {
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function (i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] + ' UTC');
val = line[1];
earnings.push([date, parseFloat(line[1].replace(',', '.'), 10)]);
});
} catch (e) {}
options.series[0].data = earnings;
chart = new Highcharts.Chart(options);
});
});
</script>
data_today.php
<?php
session_start();
require_once('config.php');
require_once('config_mysql.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if (!$db)
{
die("Unable to select database");
}
$result = mysql_query("SELECT earn_date,SUM(amount) as val FROM user_earnings WHERE user_id='$USER_ID' AND DATE(earn_date) = DATE(NOW()) GROUP BY earn_date");
if ($result)
{
while ($row = mysql_fetch_array($result))
{
$d = date("l, F, j, Y G:i:s", strtotime($row["earn_date"]));
echo $d . "\t" . $row['val'] . "\n";
}
}
else
{
die(mysql_error());
}
mysql_close($link);
?>
So, (if its not enough clear yet) I need this code to show whole day and show also empty values by hour.
I have almost zero experience of highcharts and javascript, so I need some help with this :)
Also looking for alternative way for running MySql query inside index.php so I dont need data_today.php
Thanks
Set the xAxis as below
xAxis: {
ordinal: false
}
For empty spaces you should have null values. Then set connectNulls: false.
Example

Categories