Values not display in highcharts - php

JSON output: (from dt.php)
[{
"name":"Year",
"data":[2012,2013]
},{
"name":"A",
"date":[111,24]
},{
"name":"B",
"date":[34,0]
},{
"name":"C",
"date":[365,43]
},{
"name":"D",
"date":[496,0]
}]
Javascript:
$(document).ready(function() {
var chart;
var option = {
chart: {
renderTo: 'hcChart',
type: 'column'
},
title: {
text: 'Testing'
},
xAxis: {
categories: []
},
series: []
};
$.getJSON("dt.php", function(json) {
option.xAxis.categories = json[0]['data'];
option.series[0] = json[1];
option.series[1] = json[2];
option.series[2] = json[3];
option.series[3] = json[4];
chart = new Highcharts.Chart(option);
});
});
The chart does show out with the legends but the there are no single value showing up.. Any help?

Change date to data:
[{"name":"Year","data":[2012,2013]},{"name":"A","data":[111,24]},{"name":"B","data":[34,0]},{"name":"C","data":[365,43]},{"name":"D","data":[496,0]}]
Also remember to render the chart to a div id. option.chart.renderTo = 'myChart';
Working example:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
var chart;
var option = {
chart: {
renderTo: 'hcChart',
type: 'column'
},
title: {
text: 'Testing'
},
xAxis: {
categories: []
},
series: []
};
$.getJSON("dt.php", function (json) {
option.xAxis.categories = json[0]['data'];
console.log(json);
option.series[0] = json[1];
option.series[1] = json[2];
option.series[2] = json[3];
option.series[3] = json[4];
option.chart.renderTo = 'myChart';
chart = new Highcharts.Chart(option);
});
});
</script>
<div id="myChart"></div>

Related

How to display historical data and live data from database using Highcharts

I am having difficulty figuring out how to use Highcharts to get new(live) data from a database.
I have tested the example here and it works great.
I get new data written to the database every 1min. The problem is I can only make it grab the newly inserted data from the database and update the chart every 1min, using the newly inserted data as the new data point. I can't get it to show historical data from the database.
Here is an example of what I'm trying to do.
Here is the code I´m using at the moment.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'area',
zoomType: 'x'
},
title: {
},
xAxis: {
type: 'datetime'
},
yAxis: {
},
series: [{
name: 'Download',
data: []
}, {
name: 'Upload',
data: []
}]
};
$.getJSON('data.php', function(json) {
data1 = [];
data2 = [];
$.each(json, function(key,value) {
data1.push([value[0], value[1]]);
data2.push([value[0], value[2]]);
});
options.series[0].data = data1;
options.series[1].data = data2;
chart = new Highcharts.stockChart(options);
});
});
</script>
<body>
<div id="container" style="min-width: 400px; height: 800px; margin: 0 auto"></div>
</body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
And here is the code for data.php.
<?php
$dbhost = 'localhost';
$dbname = 'highchart';
$dbuser = '*******';
$dbpass = '*******';
try{
$dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
$stmt=$dbcon->prepare("SELECT * FROM trafico");
$stmt->execute();
$json = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$json[]= [strtotime($time_1m)*1000, (int)$Tx, (int)$Rx];
}
echo json_encode($json);
?>
This is the output I get from data.php.
[[1521071984000,1255,91],[1521072190000,1212,92],[1521072241000,1220,93],[ ... ]]
This is the graph I get
Basically I don't know to how to make the code (this graph) above to update dynamically every 1min with new data points.
Problem solved.
This is the code I added:
events: {
load: function requestData() {
$.ajax({
url: 'live.php',
success: function(points) {
var series = chart.series,
shift;
$.each(series, function(i, s) {
shift = s.data.length > 1;
s.addPoint(points[i], true, true);
});
setTimeout(requestData, 1000);
chart.redraw();
},
cache: false
});
}
}
Now I have historical data from my DB and it adds new data point every time there's a new entry in de DB without the need to refresh the page.
Here is is my live.php code:
<?Php
header("Content-type: text/json");
$dbhost = 'localhost';
$dbname = 'highchart';
$dbuser = '*******';
$dbpass = '*******';
try{
$dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
$stmt=$dbcon->prepare("SELECT * FROM trafico");
$stmt->execute();
$json = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
}
$json[]= [strtotime($time_1m)*1000, (int)$Tx];
$json[]= [strtotime($time_1m)*1000, (int)$Rx];
echo json_encode($json);
?>
This is the output from live.php:
[[1522869181000,872],[1522869181000,54]]
and this is how the code looks now
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
Highcharts.setOptions({
time: {
timezoneOffset: 3 * 60
}
});
var options = {
chart: {
renderTo: 'container',
type: 'area',
zoomType: 'x',
events: {
load: function requestData() {
$.ajax({
url: 'live.php',
success: function(points) {
var series = chart.series,
shift;
$.each(series, function(i, s) {
shift = s.data.length > 1;
s.addPoint(points[i], true, true);
});
setTimeout(requestData, 1000);
chart.redraw();
},
cache: false
});
}
}
},
title: {
},
xAxis: {
type: 'datetime'
},
yAxis: {
},
series: [{
name: 'Download',
data: []
}, {
name: 'Upload',
data: []
}]
};
$.getJSON('data.php', function(json) {
data1 = [];
data2 = [];
$.each(json, function(key,value) {
data1.push([value[0], value[1]]);
data2.push([value[0], value[2]]);
});
options.series[0].data = data1;
options.series[1].data = data2;
chart = new Highcharts.stockChart(options);
});
});
</script>
<body>
<div id="container" style="min-width: 400px; height: 800px; margin: 0 auto"></div>
</body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

how can I modify my function via ajax?

well, to start I used to make my JSON function, but when I wanted add data I couldn't. So How can I my json function ? i'm using getJSON but I can't add data like ajax then how could I change it to ajax style. it's for hightchart
$(function() {
var processed_json = new Array();
$.getJSON('../controllers/chart_controller.php', function(data){
for (i = 0; i < data.length; i++){
processed_json.push([data[i].key,data[i].value]);
}
//draw chart
$('#salesChart').highcharts({
chart: {
type: "column"
},
title: {
text: "Best selling product"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: "Scores"
}
},
series: [{
name: 'Sales',
data: processed_json
}]
});
});
});

dynamic auto update highcharts using ajax from mysql database [duplicate]

I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}

highchart Dynamically updated data

i want to set up highcharts.
i made a simple random number in this url
http://echocephe.com/new/custom_number.php
i want to use these random datas on Dynamically updated data charts
this is code can you help me to solve this problem thanks.
<script type="text/javascript">
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
</script>
maybe its better to check highchart forums
here is the answer
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data/

Highcharts Pie Chart from Ajax

I have a page that uses highcharts pie chart, and I am trying to update the chart with a date selector drop down. I have a similar implementation for a bar chart and its working great. Please note (this is coming from a PHP class, hence the concatenation and what not).
<script type='text/javascript'>
function drawPie(data)
{
var chart;
alert('called');
var options = {
chart: {
renderTo: 'PieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
height: 350
},
title: {
text: 'Product Popularity'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {enabled: false},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Product Popularity',
data: data
}]
}
chart = new Highcharts.Chart(options);
$('#ProductPieMod div.mod_content').css('height', $('#PieChart').css('height'));
}
$(document).ready(function(){
drawPie(" . $this->get_data($this->date) . ");
$('#ProductPieMod_date').on('change', function(){
var val = parseInt($(this).val());
switch(val)
{
case 0:
var date = Date.today();
break;
case 1:
var date = Date.parse('last week');
break;
case 2:
var date = Date.today().moveToFirstDayOfMonth();
break;
case 3:
var date = Date.parse('January').moveToFirstDayOfMonth();
break;
default:
var date = Date.today();
}
var info;
$.ajax({
type: 'POST',
url: '". matry::base_to('utilities/dhs/manager_dash') . "',
async: false,
dataType: 'json',
data: {date: date.toString('M/dd/yyyy'), module: 'ProductPieMod'},
success: function(data)
{
drawPie(data);
}
});
});
});
</script>
My ajax returns the following string:
[['FASTCLIX LANCING DEVICE', 62.5],['FREESTYLE LANCING DEVICE', 25],['ONETOUCH DELICA LANCING DEVICE', 12.5]]
In addition, this chart is initially built, using the exact same method, just fine. Its just when I use the dropdown (run the onChange event) that it breaks.
Update
I have created a fiddle for this as well: http://jsfiddle.net/SHReZ/1/
Firts, you need to place chart var to document.ready handler scope, next, you need to destroy chart before draw.
$(document).ready(function () {
var chart;
function drawPie(data) {
console.log('called');
var options = {
chart: {
renderTo: 'PieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
height: 350
},
title: {
text: 'Product Popularity'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Product Popularity',
data: data
}]
};
if (chart !== undefined) chart.destroy();
chart = new Highcharts.Chart(options);
$('#ProductPieMod div.mod_content').css('height', $('#PieChart').css('height'));
}
drawPie([
['ONETOUCH DELICA LANCING DEVICE', 27.78],
['FREESTYLE LANCING DEVICE', 20.83],
['Nova Max Ketone Test Strips Health and', 11.11],
['ONETOUCH ULTRASOFT LANCING DEVICE 2PK', 11.11]
]);
//get data from https://gist.github.com/zba/4712055 , delay 4
$.post('/gh/gist/response.html/4712055', {
delay: 4
}, function (data) {
drawPie(data);
}, 'json');
});
fiddle
also here is demo which not destroy chart, but it change colors to much

Categories