Reputation: 1671
im totally stuck here for hours now and I can't find the error :(
I need to draw a pie chart from data I get from a database. The chart needs to be redrawn every few seconds with fresh data so I get the data (as JSON) via AJAX. No problems so far.
But now I need to get Highcharts to actually draw the new data. Seems impossible :( It just stays with the initial data - even though an alert shows me that the new data has been parsed correctly and entered into the "data" property of the chart.
can anyone please advise?
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
var chart;
var options = {
chart:
{
renderTo: 'container',
defaultSeriesType: 'column',
events:
{
load: requestData,
redraw: function(){alert("graph has just been redrawn");}
}
},
series: [
{
type: 'pie',
name: 'x',
data: [['All', 1],['more', 2]]
}]
};
function requestData()
{
$.ajax(
{
url: "http://1.2.3.4/getMeSomeJSON.php",
type: "GET",
success: function(response)
{
var json = jQuery.parseJSON(response);
var protocols = response.services.protocols;
chart.series[0].data = [];
for(var i=0; i<protocols.length; i++)
{
var tmp = protocols[i].prot;
chart.series[0].data.push({tmp: protocols[i].byte_len});
}
//alert(chart.series[0].data); // everything seems to be OK here...
// neither one works :(
//chart.redraw();
//chart = new Highcharts.Chart(options);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto; border: 1px solid black;"></div>
<script>
$(document).ready(function()
{
chart = new Highcharts.Chart(options);
});
</script>
</body>
</html>
Upvotes: 0
Views: 6188
Reputation: 26320
To update dynamically you have to use setData
, like the following.
var json = jQuery.parseJSON(response),
protocols = json.services.protocols,
data = [];
for(var i=0; i<protocols.length; i++) {
var tmp = protocols[i].prot;
data.push({tmp: protocols[i].byte_len});
}
chart.serie[0].setData(data);
Here you can see a related question.
Reference
Upvotes: 2