Highchart ID does not update with new variable - javascript

I try to generate a windrose on my website using highcharts. It should display the direction with an arrow and the speed in the gauge itself.
I have the following code to generate the charts:
$(document).ready(function() {
var chart = new Highcharts.Chart({
\\ some other parameters not relating to question
series: [{
data: [{
id: 'wnddr',
y: winddir,
dial: {
radius: '90%',
baseWidth: 3,
baseLength: '95%',
rearLength: 0
}
}],
dataLabels: {
enabled: true,
formatter : function(){
return windspd + ' km/u';
}
}
}]
},
function (chart){
setInterval(function() {
$.ajax({
type: "POST",
url: "example.php",
dataType: "JSON",
cahce: "false",
success: function(data){
windspd = data.query.results.channel.wind.speed;
winddir = data.query.results.channel.wind.direction;
windchill = data.query.results.channel.wind.chill;
hum = data.query.results.channel.atmosphere.humidity;
druk = data.query.results.channel.atmosphere.pressure;
ss = data.query.results.channel.astronomy.sunset;
sr = data.query.results.channel.astronomy.sunrise;
temp = data.query.results.channel.item.condition.temp;
des = data.query.results.channel.item.forecast[0].code;
var point = chart.series[0].points[0];
point.update(winddir);
// alert(winddir);
}
});
$('.update').html("<img src=http://l.yimg.com/a/i/us/we/52/" +des+ ".gif />");
}, 5000);
});
});
With wnddr.update(winddir); I was trying to update the winddir-variable in my chart. However, I can't get it to work. Also the alert does not pop-up so probably my code gets stuck just before. If I comment the two line above the alert out, the alert will work. Same goes for the speed-variable. Problem here is that is doesn't have a id-attribute.
I modified the code from highcharts as the basis. Giving 'y' a value by hand generates a valid and correct gauge. The same goes for a fixed value of winddir.

Related

High Charts Live Data multiple series from php files

Im fairly new to js and php , I am trying to load a live chart with mutliple series of btc price from exchanges from php files. Ive tried and failed, i can only get 1 of the data series to load , they all work individually but getting all of them to load as seperate points on the chart at the same time eludes me.
BITSTAMP.PHP -- results: [1519417809000,9932.83]
<?php
header("Content-type: text/json");
function bitstampbtcusdgetprice($url)
{ $decode = file_get_contents($url);
return json_decode($decode, true); }
$x = time() * 1000;
$y =
$btcusdgetprice('https://www.bitstamp.net/api/v2/ticker/btcusd');
$btcusdtickerprice = round(($y["last"]), 2);
$ret = array($x, $btcusdtickerprice);
echo json_encode($ret);
?>
CHART.JS
var chart;
function requestDatabitstamp() {
$.ajax({
url: 'php/bitstamp.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 100;
chart.series[0].addPoint(point, true, shift);
setTimeout(requestDatabitstamp, 30000);
},
cache: false
});
}
$(document).ready(function() {
chart = new
Highcharts.Chart({
colorAxis:{ gridlineColor: '#4c4c4c'},
marker:{ animation: '10000'},
chart:{ renderTo: 'container',
defaultSeriesType: 'line',
backgroundColor: '#141414',
borderColor: '#00A578',
plotbackgroundColor: '#161616',
parallelAxes: {linecolor: '#4c4c4c'},
events: { load: requestDatabitstamp}},
tooltip:{ style: {color: '#FFFFFF',
fontSize: '10px'},
backgroundColor: '#141414',
borderRadius: '12'},
title:{ text: '<font style="color:#FFFFFF;font-family:verdana;">Exchange Comparison</font>'},
plotOptions:{ series: {
color: '#00A578'}},
xAxis:{ type: 'datetime',
tickPixelInterval: 150,
maxZoom: 50 * 1000},
yAxis:{ minPadding: 0.2,
maxPadding: 0.2,
title:{ text: '<font style="color:#00A578;font-family:verdana;">USD</font>',
margin: 30}},
series: [{ color: '#00A578',
name: '<font align="center" style="color:#00A578;font-family:verdana;">Bitstamp</font>',
data: []
}]});});
I'm no expert with Highcharts but what I see is that you are filling only chart.series[0] with points so only one series is printed. You have to have series for each exchange.
Update:
Try creating an array filled with the data for each exchange in the PHP file and receiving it through AJAX, then create points for chart.series[1] and chart.series[2].
got it , heres the updated code. i had the other series i tried importing in the wrong places.
function requestData() {
$.ajax({
url: 'php/binance.php',
success: function(point) {
var series = chart.series[0],
shift0 = series.data.length > 50; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift0);
// call it again after one second
},
cache: false
});
$.ajax({
url: 'php/bitstamp.php',
success: function(point) {
var series = chart.series[1],
shift1 = series.data.length > 50; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift1);
// call it again after one second
},
cache: false
});
$.ajax({
url: 'php/bittrex.php',
success: function(point) {
var series = chart.series[2],
shift2 = series.data.length > 50; // shift if the series is
// longer than 20
// add the point
chart.series[2].addPoint(point, true, shift2);
// call it again after one second
setTimeout(requestData, 10000);
},
cache: false
});
}

charts.js not updating after ajax request

I'm a complete newb with js and jquery but have muddled my way through getting a chart to properly display using Flask and an Ajax request. Where I'm having a problem is getting the charts data to refresh. I can get the chart to display just fine if I create it as a new chart as shown in the code below
$(document).ready(function() {
var getdata = $.post('/charts');
var ctx = document.getElementById('myChart').getContext('2d');
var myChart
getdata.done(function(results){
var chartData = {
labels: results['month'],
datasets: [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart = new Chart(ctx, {type: 'line', data: chartData});
});
$("form :input").change(function() {
year = $(this).val();
console.log(year)
$.ajax({
type: "POST",
url: "/data",
data: {'year':year},
success: function(results){
var updatedData = {
labels : results['month'],
datasets : [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart= new Chart(ctx, {type: 'line', data: updatedData});
}
});
});
});
But if I change the last line to
myChart.update(updatedData)
nothing happens, I don't get any errors, the chart doesn't update. Nothing. The strange thing is that I know the myChart is global because I don't have to create it again after the Ajax request.
Thanks
From the documentation of charts.js (http://www.chartjs.org/docs/#getting-started-creating-a-chart), you first need to change data and then call update (arguments for update function are not the data, but duration etc.):
.update(duration, lazy)
Triggers an update of the chart. This can be safely called after replacing the entire data object. This will update all scales, legends, and then re-render the chart.
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
So in your case:
myChart.data = updatedData;
myChart.update();

Highchart xAxis label steps wrong

I am loading Highcharts like this.
var options = {
credits: {
enabled: false
},
chart: {
renderTo: 'chart_box',
type: 'areaspline'
},
title: {
text: ''
},
xAxis: {
crosshairs: true,
labels: {
step: 5,
rotation: -45
}
},
series: []
};
Then I have a function which is called when graph needs to be loaded. Upon calling the function, data is fetched through AJAX and assigned to series and date lie this:
$.ajax({
url: 'url/charts',
type: 'post',
data: data
}).done(function(data) {
var dateCount = data.dates.length;
var stepCount = 1;
if (dateCount > 10) {
stepCount = 5;
}
options.xAxis.categories = data.dates;
$.each(data.series, function(name, elem) {
options.series.push({
name: name.replace('_', ' ').toUpperCase().trim(),
data: elem
})
});
chart = new Highcharts.Chart(options);
});
The issue here is that even though I have given step as 5 , it is showing dates with 15 dates interval. I mean in xAxis labels. It seems like it will be multiplied by three always. If I give 2, it will show 6 days interval in labels. Everything working fine in a chart which is not using AJAX to load data.

Highcharts Pyramid Chart displays no data with JSON, PHP

When using JSON with a pyramid chart in Highcharts, I don't get any errors in the console log but no data is displayed.
I have charts.php which outcome is this:
{"success":1,"data":[{"name":"John Spoon","data":300}, {"name":"Dave Jones","data":200},{"name":"Other","data":500}]}
This is what I've tried, which returns no data.
<div id="chart" style=
"height:600px;width:100%;"></div>
<script>
$(function () {
$("#chart").html("Loading Activity Log Graph...");
var options = {
chart: {
type: 'pyramid',
renderTo: 'chart',
marginRight: 100
},
title: {
text: 'Activity',
x: -50
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '<b>{point.name}</b> ({point.y:,.0f})',
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
softConnector: true
}
}
},
legend: {
enabled: false
},
name: 'Activity Count',
series: [{}]
};
$.ajax({
url: "charts.php",
type:'post',
dataType: "json",
success: function(data){
options.series = data.data;
var chart = new Highcharts.Chart(options);
}
});
});
</script>
This is my desired outcome, showing without the use of JSON:
http://jsfiddle.net/0dyy44hz/
What do I need to change for it to show data?
Looking at the pyramid example, the data must be in the form of a single series with each data point as an array of [name, value]. You have two options, change your PHP to output the correct format or modify the PHP output in javascript. Since you didn't post your PHP code, I'll do the later:
var data = {"success":1,"data":[{"name":"John Spoon","data":300}, {"name":"Dave Jones","data":200},{"name":"Other","data":500}]};
options.series = [{
data: $.map(data.data, function(i){ // loop outputted data
return [[i.name, i.data]]; // coerce into an array of [name,value]
})
}];
Here's a working example.

dynamic highcharts with json data

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
});
}

Categories