Highstock json data not showing - php

Hey guys I am having trouble loading my data into the highstock charts.
My json.php calls on a sample MySQL database and looks something like this:
$result = mysql_query("SELECT UNIX_TIMESTAMP(date)*1000 AS timestamp,value from sample") or die('Could not query');
if(mysql_num_rows($result)){
echo 'Test';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
if($first) {
$first = false;
} else {
echo ',';
}
$json_str = json_encode($row, JSON_NUMERIC_CHECK);
echo $json_str;
}
if(array_key_exists('callback', $_GET)){
$callback = $_GET['callback'];
echo $callback. '('.$json_str.');';
}
} else {
echo '[]';
}
mysql_close($db);
My index.htm which calls the Json.php is from the sample highstock template I just merely changed the getJson to match with my reference. Here is the code. Any help would be much appreciated, thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('json.php', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'Test'
},
series : [{
name : 'Test',
data : data,
marker : {
enabled : true,
radius : 3
},
shadow : true,
tooltip : {
valueDecimals : 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
Also, my json is parsed in this manner:
Test[1370899026000,10],[1370899026000,4],[1368177426000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1378826226000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,9],[1370899026000,9],[1370899026000,10],[1370899026000,6],[1370899026000,6],[1370899026000,6],[1370899026000,12],[1370899026000,7],[1370899026000,12],[1370899026000,8],[1370899026000,13],[1370899026000,12],[1370899026000,9],[1370899026000,7],[1370899026000,7],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,9],[1370899026000,10],[1370899026000,4],[1370899026000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1370899026000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7]

Try closing with
[]
Highstock fiddle: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/areaspline/
Data of that fiddle: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?

Please take look at http://docs.highcharts.com/#preprocessing-data-from-a-database and take look at very simple example with json_encode:
tmp = array();
$tmp[] = array('A',5);
$tmp[] = array('B',6);
$tmp[] = array('C',1);
$tmp[] = array('D',2);
$rows = array();
for($i=0; $i<count($tmp); $i++)
{
$row['name'] = $tmp[$i][0];
$row['data'] = array($tmp[$i][1]);
array_push($rows,$row);
}
print json_encode($rows);
Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{
name: 'Browser share',
data: []
}]
}
$.getJSON("datavotecolum.php", function(json) {
console.log(json);
options.series = json;
chart = new Highcharts.Chart(options,function(chart){
console.log(chart.series);
});
});
});

Related

Errror when trying to display SQL data from Microsoft SQL Server Management Studio to graph in canvasjs

Heres the code:
I tried converting the code from mysql to mysqlsrv which has been a mess. I need to display values from the database onto a graph.
<?php
require 'conn.php';
$dataPoints = array();
try{
$link = $conn;
$handle = "select Lolo_Setpoint, Hihi_Setpoint from Alarms";
$result = sqlsrv_query($conn,$handle);
foreach ((array) $result as $row)
{
array_push($dataPoints, array("x"=> $row[0], "y"=> $row[1]));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "PHP Column Chart from Database"
},
data: [{
type: "line", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
The result is just a blank screen

JSON data not showing in highstock candlestick chart using PHP and SQL

I'm trying to display a highstock candlestick chart, but I can't achieve it.
My website shows a blank where the chart should be, but there's nothing showing in the chart.
How can I fix it to show the chart?
I have two scripts:
datachart.inc.php:
<?php
include '../dbh.php'; //It connects to the database
$sql = "SELECT * from table";
$result = $conn->query($sql);
$row = mysqli_fetch_array($result);
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array($newdate, (float)$row['open'], (float)$row['high'],
(float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
?>
index.htm:
<!DOCTYPE HTML>
<HTML>
<BODY>
<script>
$(function() {
$.getJSON('datachart.inc.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'Test Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
</script>
<div id="container" style="height: 250px; min-width: 250px"></div>
</BODY>
</HTML>
Click here to see a picture of my sql table
Solved:
1) Import the javascript files
2) Remove "$row = mysqli_fetch_array($result);"
3) Change "while ($row=mysql_fetch_array($result))" to "while ($row=mysqli_fetch_array($result))"

How do I import PHP array in a JSON array?

So I have a PHP script where I ask a simple query and then I put it in an array.
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
The outcome of print json_encode($data) is:
[{"ATX12V":"10"},{"ATX12V":"65"},{"ATX12V":"64"},{"ATX12V":"96"}]
Below I have a javascript code and my question is how do I add $data to the data[]??
<script>
var buyerData = {
labels : ["January","February","March","April","May","June", "July", "August"],
datasets : [
{
fillColor : "#9DB86D",
strokeColor : "#ACC26D",
pointColor : "#9DB86D",
pointStrokeColor : "#9DB86D",
data : []
}
]
}
</script>
What about simple:
data : <?php echo json_encode($data); ?>
you can use ajax like :
(home.html):
<script type="text/javascript">
window.onload = function() {
$.ajax({
type: "POST",
url: "request.php",
dataType: "json",
success: function (data) {
alert(data[0].ATX12V);
}
});
}
</script>
<script type="text/javascript" src="js/jquery.js"></script>
and server side (request.php) :
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
note: Add jquery.js in your project

Highcharts and php for a dynamic chart

I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";
You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub
Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.

load data from text file into HIGHCHART graphic using PHP

I need to read data from text file that have many lines to load into highchart but if I put it as many lines, it will show the messy text please see this link. I don't want like this, I want that if have more than 20 lines in text file, it should be display 2 or 3 graphic of highchart to make the text is easy to see.I have the PHP code and script code as below:
<?php
$PMTA_DATE = date("Y-m-d");
$PMTA_FILE = file_get_contents("../stats_domain_emetteur.switchcall.com.".$PMTA_DATE.".txt");
$lineFromText = explode("\n", $PMTA_FILE);
//$number_bar_charts = 12;
$row = 0;
$cate = "";
$total ="";
$fail = "";
$mailSuc = "";
$title = "";
foreach($lineFromText as $line){
// if($row < $number_bar_charts){
$words = explode(";",$line);
$dateTime .= ','.$words[0];
if($title == ""){
$title = $words[0];
}
$cate .= ','."'$words[5]'";
$total .= ','.$words[6];
$fail .= ','.$words[7];
$mailSuc .= ','.((int)$words[6] - (int)$words[7]);
$row++;
// }
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Colunm Stack Percent Chat</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'PMTA4',
type: 'column'
},
title: {
text: 'PMTA4 - Unitead.info -<?php echo $title;?>'
},
xAxis: {
categories: [<?php echo substr($cate,1);?>]
},
yAxis: {
min: 0,
title: {
text: '% envoi'
}
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y +' ('+ Math.round(this.percentage) +'%)';
}
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: [{
name: 'Total mail succesful',
data: [<?php echo substr($mailSuc,1);?>]
}, {
name: 'Total mail fail',
data: [<?php echo substr($fail,1);?>]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="PMTA4" style="min-width: 400px; height: 200px; margin-top:10px;"></div>
</body>
</html>
I do not know how to fix this, anyone help me please,Thanks.
If you take a look the reference you'll see that you can style labels.
Using staggerLines to display the label in more than one line, but it's not a good way and you can see why on my demo.
xAxys: {
labels: {
staggerLines: 10
}
}
demo
Or you can try to rotate them.
xAxys: {
labels: {
rotate: 90, // you can use 45 or 60 for a better readability
align: 'left'
}
}
demo
Reference:
http://api.highcharts.com/highstock#xAxis.labels.staggerLines

Categories