Data won't echo on Highcharts - php

I can't get my data to plot on the highchart but it shows up on the source, what am I doing wrong? I don't know if I am using the wrong syntax to echo my string from the hcdata.php. I have been having this problem with getting the output to show up on the actual chart from what I can see the data is correctly formatted it comes out like this:
[Date.UTC(2013,05,31,10,39,36), 20179],
[Date.UTC(2013,05,31,10,30,00), 20031],
[Date.UTC(2013,05,31,10,09,36), 19684],
[Date.UTC(2013,05,31,09,54,36), 19384],
[Date.UTC(2013,05,31,09,39,36), 19039],
[Date.UTC(2013,05,31,09,24,36), 18763],
[Date.UTC(2013,05,31,09,09,36), 18435],
[Date.UTC(2013,05,31,08,54,36), 18097],
[Date.UTC(2013,05,31,08,39,36), 17788],
[Date.UTC(2013,05,31,08,30,00), 17552],
[Date.UTC(2013,05,31,08,09,36), 17169],
[Date.UTC(2013,05,31,08,00,00), 16940],
[Date.UTC(2013,05,31,07,45,00), 16608],
[Date.UTC(2013,05,31,07,30,00), 16284],
[Date.UTC(2013,05,31,07,15,00), 15922],
[Date.UTC(2013,05,31,06,54,36), 15216],
[Date.UTC(2013,05,31,06,39,36), 14724],
[Date.UTC(2013,05,31,06,30,00), 14352],
[Date.UTC(2013,05,31,06,09,36), 13713],
[Date.UTC(2013,05,31,05,54,36), 13491],
[Date.UTC(2013,05,31,05,39,36), 13660],
[Date.UTC(2013,05,31,05,24,36), 13680],
[Date.UTC(2013,05,31,05,09,36), 13548],
[Date.UTC(2013,05,31,04,54,36), 13327],
[Date.UTC(2013,05,31,04,45,00), 13263],
[Date.UTC(2013,05,31,04,30,00), 13178],
[Date.UTC(2013,05,31,04,09,36), 13105],
[Date.UTC(2013,05,31,03,54,36), 13048],
[Date.UTC(2013,05,31,03,39,36), 13054],
[Date.UTC(2013,05,31,03,24,36), 13079],
[Date.UTC(2013,05,31,03,15,00), 13138],
[Date.UTC(2013,05,31,03,00,00), 13200],
[Date.UTC(2013,05,31,02,39,36), 13330],
[Date.UTC(2013,05,31,02,24,36), 13409],
[Date.UTC(2013,05,31,02,15,00), 13512],
[Date.UTC(2013,05,31,01,54,36), 13675],
[Date.UTC(2013,05,31,01,39,36), 13825],
[Date.UTC(2013,05,31,01,24,36), 13986],
[Date.UTC(2013,05,31,01,15,00), 14143],
[Date.UTC(2013,05,31,00,54,36), 13851],
[Date.UTC(2013,05,31,00,39,36), 14066],
[Date.UTC(2013,05,31,00,24,36), 14303],
[Date.UTC(2013,05,31,00,09,36), 14591]
<?php include "data.php"; ?>
<?php include "hcdata.php"; ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript" src="''/SQLPHP/js/jquery.min.js"></script>
<script src="''/SQLPHP/js/highcharts.js"></script>
<script src="''/SQLPHP/js/modules/exporting.js"></script>
<script type="text/javascript">
$(function () {
var data = [
[<?php echo $finalString; ?>]
];
data.sort(function(a,b) {
return a[0] - b[0];
});
$('#container').highcharts({
chart: {
type: 'spline'
},
title: {
text: 'Forecast vs Actual Load [VM]'
},
subtitle: {
text: 'This chart displays the time and actual forecast load for this region'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Actual Load (WM)'
},
min: 0
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%e. %b', this.x) +': '+ this.y +' m';
}
},
series: [{
name: 'Forecast vs Actual Load',
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
data: data
}]
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

Your PHP data insert looks like it is wrapping the data in 2 [] blocks:
var data = [
[<?php echo $finalString; ?>]
];
You need to wrap your entire data set in one []. Such that it looks like:
var data = [
<?php echo $finalString; ?>
];
You should end up with this:
[
[Date.UTC(2013,05,31,10,39,36), 20179], [Date.UTC(2013,05,31,10,30,00), 20031], [Date.UTC(2013,05,31,10,09,36), 19684], [Date.UTC(2013,05,31,09,54,36), 19384], [Date.UTC(2013,05,31,09,39,36), 19039], [Date.UTC(2013,05,31,09,24,36), 18763], [Date.UTC(2013,05,31,09,09,36), 18435], [Date.UTC(2013,05,31,08,54,36), 18097], [Date.UTC(2013,05,31,08,39,36), 17788], [Date.UTC(2013,05,31,08,30,00), 17552], [Date.UTC(2013,05,31,08,09,36), 17169], [Date.UTC(2013,05,31,08,00,00), 16940], [Date.UTC(2013,05,31,07,45,00), 16608], [Date.UTC(2013,05,31,07,30,00), 16284], [Date.UTC(2013,05,31,07,15,00), 15922], [Date.UTC(2013,05,31,06,54,36), 15216], [Date.UTC(2013,05,31,06,39,36), 14724], [Date.UTC(2013,05,31,06,30,00), 14352], [Date.UTC(2013,05,31,06,09,36), 13713], [Date.UTC(2013,05,31,05,54,36), 13491], [Date.UTC(2013,05,31,05,39,36), 13660], [Date.UTC(2013,05,31,05,24,36), 13680], [Date.UTC(2013,05,31,05,09,36), 13548], [Date.UTC(2013,05,31,04,54,36), 13327], [Date.UTC(2013,05,31,04,45,00), 13263], [Date.UTC(2013,05,31,04,30,00), 13178], [Date.UTC(2013,05,31,04,09,36), 13105], [Date.UTC(2013,05,31,03,54,36), 13048], [Date.UTC(2013,05,31,03,39,36), 13054], [Date.UTC(2013,05,31,03,24,36), 13079], [Date.UTC(2013,05,31,03,15,00), 13138], [Date.UTC(2013,05,31,03,00,00), 13200], [Date.UTC(2013,05,31,02,39,36), 13330], [Date.UTC(2013,05,31,02,24,36), 13409], [Date.UTC(2013,05,31,02,15,00), 13512], [Date.UTC(2013,05,31,01,54,36), 13675], [Date.UTC(2013,05,31,01,39,36), 13825], [Date.UTC(2013,05,31,01,24,36), 13986], [Date.UTC(2013,05,31,01,15,00), 14143], [Date.UTC(2013,05,31,00,54,36), 13851], [Date.UTC(2013,05,31,00,39,36), 14066], [Date.UTC(2013,05,31,00,24,36), 14303], [Date.UTC(2013,05,31,00,09,36), 14591]
]

Related

Produce highcharts multiple line chart from JSON / MySQL data

Firstly I apologise, I am not a programmer (but I am learning - slowly). I am interested in graphs for Horticultural applications. I have a database that gets data from sensors on an hourly basis and the query grabs the last 12 to 48 readings, according to the select statement. With help from your forum, I have created 3 files that together extract the data from MySQL to plot a graph with multiple series of: Timestamp (with various options for display), temperature and humidity.
I based my work on this example in fiddle https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-basic which uses data provided 'in the script' but after three weeks I can't inject the data from JSON
The first of my files makes the MySQL db connection, the second file extracts and formats the data into JSON data and the third is supposed to create the graph but doesn't :-(.
this is what is produced with a series label for each row, rather than a line for each series.
Can you help me? I would like a line graphs showing temperature and humidity. Time/date along the bottom x-axis, the left y-axis temperature in degrees and a right-hand y-axis showing percentage humidity. Am I asking too much?
Finally can I please request no Ajax, or other "stuff" other than php, html, JSON, and javascripts if possible?
Any help on formatting my question would be much appreciated :-)
<?php $json_data = include ('nw_database02.php');?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Line Graph</title>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<div id="container"></div>
<script type="text/javascript">
Highcharts.chart('container', {
title: {
text: 'Temperature and Humidity'
},
subtitle: {
text: 'Source: Greenhouse1'
},
yAxis: {
title: {
text: 'Temperature'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: <?= $json_data?> ,
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
</body>
</html>
...
If I echo the $json_data I get this type of result, but bear in mind it is dynamic data and changes every hour so it must be read from json_data every time the page is accessed:
[{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},{"Timestamp":"10:35 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"10:50 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:06 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:21 02/01/21","temperature":"7","humidity":"63"},{"Timestamp":"11:34 02/01/21","temperature":"10","humidity":"66"},{"Timestamp":"04:21 02/01/21","temperature":"15","humidity":"64"},{"Timestamp":"04:36 02/01/21","temperature":"16","humidity":"61"},{"Timestamp":"04:51 02/01/21","temperature":"15","humidity":"59"},{"Timestamp":"05:07 02/01/21","temperature":"15","humidity":"60"},{"Timestamp":"05:22 02/01/21","temperature":"14","humidity":"61"}]
You need to format your data to the series structure required by Highcharts. The rest of the requirements are achievable by using chart options - please check xAxis and yAxis properties in API.
var data = <?= $json_data?>
var series = [{
name: "temperature",
data: []
},
{
name: "humidity",
data: [],
yAxis: 1
}
];
data.forEach(function(dataEl) {
series[0].data.push([
new Date(dataEl.Timestamp).getTime(),
Number(dataEl.temperature)
]);
series[1].data.push([
new Date(dataEl.Timestamp).getTime(),
Number(dataEl.humidity)
]);
});
Highcharts.chart('container', {
series: series,
yAxis: [{
title: {
text: 'temperature'
}
},
{
title: {
text: 'humidity'
},
opposite: true
}
],
xAxis: {
type: 'datetime'
}
});
Live demo: http://jsfiddle.net/BlackLabel/aw95vek6/
API Reference: https://api.highcharts.com/highcharts/series.line.data
you can achive with below code but when you choosing chart first know the purpose and create json data accroding to the series use apexcharts for free
<script type="text/javascript">
var data=[{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},{"Timestamp":"10:35 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"10:50 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:06 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:21 02/01/21","temperature":"7","humidity":"63"},{"Timestamp":"11:34 02/01/21","temperature":"10","humidity":"66"},{"Timestamp":"04:21 02/01/21","temperature":"15","humidity":"64"},{"Timestamp":"04:36 02/01/21","temperature":"16","humidity":"61"},{"Timestamp":"04:51 02/01/21","temperature":"15","humidity":"59"},{"Timestamp":"05:07 02/01/21","temperature":"15","humidity":"60"},{"Timestamp":"05:22 02/01/21","temperature":"14","humidity":"61"}];
console.log(data);
var timestamp=[];
var temperature=[];
var humidity=[];
$.each(data, function(i, item) {
console.log(data[i]);
timestamp.push(data[i].Timestamp);
temperature.push(data[i].temperature);
humidity.push(data[i].humidity);
});
Highcharts.chart('container', {
title: {
text: 'Solar Employment Growth by Sector, 2010-2016'
},
subtitle: {
text: 'Source: thesolarfoundation.com'
},
yAxis: {
title: {
text: 'Number of Employees'
}
},
xAxis: {
categories: timestamp,
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: [{
name: 'temperature',
data: temperature
}, {
name: 'humidity',
data: humidity
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>

highchart load the chart but not the JSON data

I'm trying to use highcharts to draw data from php json.
the php works ok but i dont know how to make the json an input.
Speciffically 'm trying to put the data on single Gauge Chart like the one on the example, but i can't configure the script to read the json.
The URL si this: php/KPItonsStock.php
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) AS data
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$data = getArraySQL();
echo json_encode(($data), JSON_NUMERIC_CHECK);
and the result is this:
[{"data":29655.88482666}]
so i need to put information from that URL to the gauge chart.
Im trying with getjson, but I'm missing something, because the chart loads but not the data.
This is the otriginal highchart example
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/gauge-solid/
This is the example with my data
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<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 src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/solid-gauge.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
function visitorData (data) {
$('#container').highcharts({
chart: {
type: 'solidgauge'
},
title: {
text: 'Average Visitors'
},
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
yAxis: {
min: 0,
max: 40000,
title: {
text: 'Speed'},
stops: [
[0.1, '#55BF3B'], // green
[0.5, '#DDDF0D'], // yellow
[0.9, '#DF5353'] // red
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 400,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
}
},
series: data,
});
}
$(document).ready(function() {
$.ajax({
url: 'report2/KPItonsStock.php',
type: 'GET',
async: true,
dataType: "json",
success: function (data) {
visitorData(data);
}
});
});
</script>
</head>
<body>
<div style="width: 600px; height: 400px; margin: 0 auto">
<div id="container" style="width: 300px; height: 200px; float: left"></div>
</div>
</body>
</html>
I get the graphic but it doesnt load any data
Data needs to be an array. Make your backend return
[{
"data": [29655.88482666]
}]
http://jsfiddle.net/nicholasduffy/openzant/3/

Trouble getting value from php and display on html [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have two files. One is tempTesting.php and another is using flot to graph the data displayed on project.html. But I cannot get the value from the tempTesting.php and display it on project.html.
When I run the project.html it gives me a syntax error on this line:
var dat = <?php echo $return; ?>;
tempTesting.php
<?php
$return="[123456789,22.55],[234567891,22.32]";
$maxtemp=-10;
$mintemp=50;
?>
project.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flot For Temperature Project</title>
<script src="jquery.js" language="javascript" type="text/javascript"></script>
<script src="jquery.flot.js" language="javascript" type="text/javascript"></script>
<!--[if IE]><script language="javascript" type="text/javascript" src="excanvas.pack.js"></script><![endif]-->
<script type="text/javascript" src="jquery.flot.time.js"></script>
<script type="text/javascript" src="jquery.flot.symbol.js"></script>
<script type="text/javascript" src="jquery.colorhelpers.js"></script>
<script type="text/javascript" src="jquery.flot.canvas.js"></script>
<script type="text/javascript" src="jquery.flot.categories.js"></script>
<script type="text/javascript" src="jquery.flot.crosshair.js"></script>
<script type="text/javascript" src="jquery.fillbetween.js"></script>
<script type="text/javascript" src="jquery.flot.image.js"></script>
<script type="text/javascript" src="jquery.flot.navigate.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
var dat = <?php echo $return;?>;
var options = {
xaxis: { mode: "time", timeformat: "%h:%M %d.%m.%y", labelWidth: "10" },
series: {
lines: { show: true, fill: true, fillColor: "rgba(0,0,0,0.2)" },
points: { show: true, fill: false },
shadowSize: 5,
color: "rgba(0,0,0,0.8)"
},
grid: { hoverable: true, clickable: true },
yaxis: { min: <?php echo $mintemp-2;?> , max: <?php echo $maxtemp+2;?>, tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"°C" }},
selection: { mode: "x", color: "rgba(125,0,0,0.6)" },
legend: { show: true, position: "se", backgroundOpacity: 0.4, backgroundColor: "rgb(255,255,255)", labelBoxBorderColor: "rgb(0,0,0)"},
};
var plot = $.plot($("#placeholder"),[ { data: dat, label: "Study Temp", color:"#333"} ], options);
var overview = $.plot($("#overview"), [ { data: dat, label: "Min: °C, Max: °C", color: "#333"} ], {
series: {
color: "rgba(0,0,0,0.8)",
lines: { show: true, lineWidth: 1, fill: true, fillColor: "rgba(0,0,0,0.2)" },
shadowSize: 0
},
xaxis: { ticks: [], mode: "time" },
yaxis: { ticks: [], min: 0, autoscaleMargin: 0.1 },
selection: { mode: "x", color: "rgba(125,0,0,0.6)" },
legend: { show: true, position: "se", backgroundOpacity: 1, backgroundColor: "rgb(255,255,255)", labelBoxBorderColor: "rgb(0,0,0)" }});
$("#placeholder").bind("plotselected", function (event, ranges) {
plot = $.plot($("#placeholder"), [dat],
$.extend(true, {}, options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
}));
overview.setSelection(ranges, true);
});
$("#overview").bind("plotselected", function (event, ranges) {
plot.setSelection(ranges);
});
var humanTime;
var jstime;
function showTimes(t) {
var datum = new Date(parseFloat(t));
humanTime = datum.toUTCString();
}
function showTooltip(x, y, contents) {
$('' + contents + '').css( {
position: 'absolute',
display: 'none',
top: y + 25,
left: x + 0,
border: '2px solid #777',
padding: '2px',
'font-family': 'Arial',
'font-size:': '1.2em',
'font-weight': 'bold',
'background-color': '#ddd',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(0),
y = item.datapoint[1].toFixed(2);
showTimes(x);
showTooltip(item.pageX, item.pageY,
y + "°C (at " + humanTime + "+1000)");
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
});
</script>
</head >
<body>
<?php
include('tempTesting.php');
?>
<div id="placeholder" style="height:300px;width=100px;"></div>
<div id="overview"></div>
<p>Flot Temperature realtime update. Below here is the Information</p>
</body>
</html>
Try var dat = "<?php echo $return; ?>"; instead.
Without quotes, if $return contains a string, javascript will interpret it as a variable, which is I think not the desired result.
Also, I you didn't set you server configuration to execute PHP in HTML files, this won't work since your file has a '.html' extension. Just rename your file to 'project.php' and it should be OK.
You cannot call PHP functions within a Javascript script. When the page loads, PHP is rendered first, followed by CSS and Javascript. So the line var dat = <?php echo $return;?>; wouldn't run properly.
Instead, you can use an Ajax request. Example here.
EDIT: Understood the question wrong. You cannot use PHP functions within a Javascript function dynamically. However, accessing just an echo command works.

Highcharts -- Getting categories from mysql

I am trying to get data from my mysql into Highcharts bar graph. I have the data from mysql that includes a port number and average bytes per port. Here is what I have for my php query and html page. The data (average bytes) shows up on the graph just fine. I can't get the categories (port) data to display.
<?php
$con = mysql_connect("localhost","root","kdkdkdk") or die(mysql_error());
mysql_select_db("silk", $con);
$result = mysql_query("SELECT dstPortNum,avgByte FROM statistic_avgbytesport ORDER BY avgByte DESC LIMIT 10;");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
#print json_encode($rows[0][0], JSON_NUMERIC_CHECK);
mysql_close($con);
?>
And my html page to display the graph.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Pie Chart</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'avgbytes'
},
title: {
text: 'Average Bytes Per Port'
},
pane: {
size:'80%'
},
xAxis: {
title: {
text: 'PORTS'
},
categories: []
},
yAxis: {
min: 0,
title: {
text: 'Bytes'
}
},
series: [{
type: 'bar',
name: 'Average Bytes',
data: []
}]
}
$.getJSON("averageBytesPerPort.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
</head>
<body>
<div id="avgbytes" style="width: 300px; height: 300px; margin: 0 auto"></div>
</body>
</html>
You can use something like this:
$.getJSON("averageBytesPerPort.php", function(json) {
var options = {
chart: {
renderTo: 'avgbytes'
},
title: {
text: 'Average Bytes Per Port'
},
pane: {
size:'80%'
},
xAxis: {
title: {
text: 'PORTS'
},
categories: data.categories
},
yAxis: {
min: 0,
title: {
text: 'Bytes'
}
},
series: [{
type: 'bar',
name: 'Average Bytes',
data: data
}]
}
chart = new Highcharts.Chart(options);
});
how the hell on earth your data is shown , you have not put the $conn as the second parameter of the
mysql_query();
it should be
$result = mysql_query("SELECT dstPortNum,avgByte FROM statistic_avgbytesport ORDER BY avgByte DESC LIMIT 10;",$conn);

mysql highcharts php rtg

First I want to say that I have looked at stackoverflow and highcharts forum, but have not been able to find a answer to my question, so I hope some kind soul can provide me with a working example of my problem.
I am trying to create a spline chart (not auto updating) from data in a mysql db created by rtg (rtg.sourceforge.net)
I am not a programmer, so please bear with me, for not creating clean/proper code (this includes copy/paste from several other sources).
There is 3 tables id (INT) , dtime (DATETIME) and counter (BIGINT) with the following sample:
1 2012-03-05 17:49:06 16991
2 2012-03-05 17:50:06 3774
3 2012-03-05 17:50:06 1272
(1,2,3 is the interface names)
I am trying to create with a chart that will show traffic for the last hour.
This is the content of my data.php
<?php
$con = mysql_connect("localhost","root","XXXXXXXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("rtg", $con);
$result = mysql_query("SELECT * FROM ifInOctets_1 ORDER BY dtime DESC LIMIT 0,60");
while($row = mysql_fetch_array($result)) {
echo $row['dtime'] . "\t" . $row['counter']. "\n";
}
mysql_close($con);
?>
The output from data.php is in the following format:
2012-03-05 20:53:31 245891 2012-03-05 20:53:31 8530 2012-03-05 20:53:31 6424577
rtg is polling 3 times pr min, so this results in 180 output "fields" from the above sql query.
This is the content of my index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Chart 1 Hour</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/gray.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
credits: {
enabled: false
},
title: {
text: 'Bits',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000, // one hour
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%Y%m%d%H%M%S', this.value);
}
}
},
yAxis: {
title: {
text: 'Bits'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%Y%m%d%H%M%S', this.x-(1000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'BlaBla'
}]
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
// This data is obtained by exporting a GA custom report to TSV.
// http://api.jquery.com/jQuery.get/
jQuery.get('data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container" style="width: 960px; height: 250px; margin: 0 auto"></div>
</body>
</html>
When I run the code it looks like all the data is cramped to the left side of the chart.
(Sorry could not post a screenshot, first time user.)
Since highcharts needs the the date + time in miliseconds, I have tried (among several other sql select statements) to change the Highcharts.dateFormat but without any luck.
Thanks in advance.
You need to convert your return date to return as the number of milliseconds since the epoch.
So SELECT * FROM ifInOctets_1 ORDER BY dtime DESC LIMIT 0,60 would become:
`SELECT UNIX_TIMESTAMP(dtime)*1000,counter FROM ifInOctets_1 ORDER BY dtime DESC LIMIT 0,60"
That way you have the correct timestamp in ms value that highcharts expects.

Categories