Highcharts live data, json ajax - php

My head is going to blow.
livedata.php loads json when page open.
live.php add point to graph.
From livedata.php i got output like this:
[["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37]]
live.php output - only last row, looks like
["Date.UTC('.2016, 07-1, 29, 15, 40.')", 44]
I've got chart, live addPoint working, but no date on x-axis. What i do wrong?
JS
var chart;
function requestData() {
$.ajax({
url: 'live.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 120; // shift if the series is
chart.series[0].addPoint(eval(point));
setTimeout(requestData, 10000);
},
cache: false
});
}
$(function () {
$.ajax({
url: 'livedata.php',
success: function(point) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
events: {
load: requestData
}
},
title: {
text: 'Revenue vs. Overhead',
},
subtitle: {
text: '',
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
name: 'Random data',
data: eval(point )
}]
});
},
});
});
live.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata order by id desc limit 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = "Date.UTC('.$date_raw.')";
$ar = array($date_complete, $row[humidity]);
echo json_encode($ar, JSON_NUMERIC_CHECK);
livedata.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata');
$result = $stmt->fetchAll();
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = [$date_complete, $row[humidity]];
}
echo json_encode($hum_for_chart, JSON_NUMERIC_CHECK);
Chart:
Chart

I think its problem of your data try to make string like,
live.php
....
$date_complete = "Date.UTC('.$date_raw.')";
$ar = "[".$date_complete.",". $row[humidity]."]";
echo json_encode($ar);
livedata.php
....
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = "[".$date_complete.",". $row[humidity]."]";
}
....
You can refer highcharts-data-series-issue-with-ajax-json-and-php

i've got it! 2 days of mind blowing ))))
Thanks to Rohan Kumar for link.
I made changes from date.utc to unix timestamp.
$datetimeUTC = ((strtotime($row[dataa])+ 10800) * 1000);
$data[] = [$datetimeUTC, $row[humidity]];
echo json_encode($data);
10800 - that is +3 hours (Moscow timezone)
The output is
[[1469718529000,37],[1469718529000,37],[1469718530000,37],[1469718531000,37]]
And that's it, date axis started working!

Related

Load data from database to set highchart X-axis with php json data

new to this and (almost) desperate. in below code i want to set $rows1['date'][] = $data['tanggal']; data as X-Axis in highchart :
$(function () {
var chart;
$(document).ready(function() {
getAjaxData(1);
var val = location.search.split('proyek=')[1]
getAjaxData(val);
function getAjaxData(proyek){
$.getJSON("src/json/data.php", {proyek: proyek}, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve-proyek',
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false,
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%Y-%m-%d', this.value);
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series: json
});
});
};
});
});
my data.php :
<?php
header("Content-type: application/json");
require_once "database.php";
$db = new database();
$mysqli = $db->connect();
$proyek = $_GET['proyek'];
$sql = "SELECT fren_pr FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows = array();
$rows['name'] = 'Rencana';
$rows['color'] = '#50B432';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows['data'][] = array($data['fren_pr'],);
}
$sql = "SELECT freal_pr, tanggal FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows1 = array();
$rows1['name'] = 'Realisasi';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows1['data'][] = $data['freal_pr'];
$rows1['date'][] = $data['tanggal'];
}
$rslt = array();
array_push($rslt, $rows);
array_push($rslt, $rows1);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$mysqli->close();
this is my json view :
I've spent a lot of time trying to solve it but haven't found a solution until now.
Is there an error in my php code?
hope someone will be kind enough to help, Thanks in advance.

Highcharts multiple series json from php

Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*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: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo

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"}]

Getting Data from Database for HighCHarts

I am developing a tool which has a statistic page on which I am using HighCharts, I am using the basic line chart, Now to populate this chart I need some data. The data comes from my DB.
I got a query which extracts a list of users assigned to a particular 'Manager', Now I want each name to appear a s different line.
But What happens is that all names appear under one line........
My code:
<?php
session_start();
class ManagerStats{
public function con()
{
require_once('connect.php');
$DB = new dbConnect();
return $DB->connect();
}
public function DontEvenKnow(){
if($_SESSION['user'] == 'manager1#gmail.com'){
$sql = "SELECT user_id, first_name FROM tbl_user WHERE user_team='bob'";
$query = mysqli_query($this->con(), $sql);
if($query){
foreach($query as $v){
echo $v;
}
}
}elseif($_SESSION['user'] == 'manager2#gmail.com'){
//$sql = "SELECT user_id FROM tbl_user WHERE user_team='oli'";
}
}
}
?>
<script>
$(function () {
$('#home_manager').highcharts({
title: {
text: '',
x: -20 //center
},
xAxis: {
categories: ['04/19', '04/20', '04/21', '04/22', '04/23', '04/24']
},
yAxis: {
title: {
text: 'Emails Sent'
},
plotLines: [
{
value: 0,
width: 1,
color: '#808080'
}
]
},
tooltip: {
valueSuffix: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [
{
name: '<?php $oko = new ManagerStats(); $oko->DontEvenKnow(); ?>',
data: [38, 78, 12, 80, 75]
},
{
name: 'Helena',
data: [23, 34, 55, 67, 34]
},
{
name: 'Martin',
data: [34, 35, 55, 69, 67]
},
{
name: 'Marta',
data: [43, 64, 75, 57, 64]
},
{
name: 'Samuel',
data: [63, 64, 75, 87, 44]
},
{
name: 'Carter',
data: [43, 54, 55, 67, 84]
}
]
});
});
</script>
In your function :
$data = "";
$data_for_user = "[43, 54, 55, 67, 84]";
//For each user you need to get data from database,
//but don't do a query inside a loop because it kills perfomance
foreach($query as $v){
$data .= " {
name: '".$v["first_name" ]."',
data: ".$data_for_user."
}, ";
}
echo $data;
then in series
series: [<?php $oko = new ManagerStats(); $oko->DontEvenKnow(); ?>]
This will do a new line on highcharts foreach user that you have
UPDATE: was missing one of the quotes on the array that might be why it wasn't working for the person if they just copied it.
UPDATE:
Getting data for more users for highcharts
You need a query with users and all his values that have to be in the graph:
$query = "SELECT t.user_id, t.first_name, group_concat( v.values ) as data_for_user
FROM tbl_user t,tbl_values v
WHERE t.user_id = v.user_id
GROUP by t.user_id";
Group concat get the values for user separated by comma the way you need for highcharts.
Remember that group_concat have a lenght limit of 1024 but you can change it with this before your query.
'SET GLOBAL group_concat_max_len=15000'
And data for highcharts
$data = "";
foreach($query as $v){
$data .= " {
name: '".$v["first_name" ]."',
data: [".$v["data_for_user"]."]
}, ";
}
Try adding a line break after you echo out the variable. Something like this:
echo $v . "<br />";
That should create a new line after each user.

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