Closed yanshiqiang closed 9 years ago
You could try something like the following, using JsExpression to encode the javascript part.
use miloschuman\highcharts\Highcharts;
use yii\web\JsExpression;
echo Highcharts::widget([
'options' => [
'chart' => [
'events' => [
'load' => new JsExpression("function () {
var series = this.series[0];
setInterval(function () {
$.getJSON('http://url-to-json-file/index.php', function (jsondata) {
series.data = JSON.parse(jsondata.cpu);
});
}, 5000);")
],
],
// ...
]
]);
Hi Milo,
Can you please check what is wrong with my code? I can't get the graph updated. Many thanks
Controller: `public function actionJsondata() {
if( Yii::$app->request->isAjax )
{
$data = [
[
'name' => 'CN',
'data' => [55, 22, 3, 14],
],
[
'name' => 'ID',
'data' => [12, 53, 7, 16],
],
[
'name' => 'THB',
'data' => [22, 13, 7, 26],
],
];
return Json::encode($data, true);
}
}`
View:
echo Highcharts::widget([ 'scripts' => [ 'modules/exporting', 'themes/grid-light', ], 'options' => [ 'chart' => [ 'type' => 'column', 'height' => 300, 'events' => [ 'load' => new JsExpression('function(){ var series = this.series[0]; setInterval(function () { $.getJSON("/test/jsondata", function (data) { series.data = JSON.parse(data); }); }, 5000); }'), ], ], 'title' => [ 'text' => 'Active Players', ], 'xAxis' => [ 'categories' => $chartLabel, ], 'yAxis' => [ 'min' => 0, 'title' => [ 'text' => 'Total Players', ], 'stackLabels' => [ 'enabled' => true, 'style' => [ 'fontWeight' => 'bold', 'color' => '(Highcharts.theme && Highcharts.theme.textColor)' || 'gray', ] ] ], 'plotOptions' => [ 'column' => [ 'stacking' => 'normal', 'dataLabels' => [ 'enabled' => true, 'color' => '(Highcharts.theme && Highcharts.theme.dataLabelsColor)' || 'white', ], 'enableMouseTracking' => false, ] ], 'series' => [ [ 'name' => 'CN', 'data' => [3, 2, 3, 4], ], [ 'name' => 'ID', 'data' => [2, 3, 7, 6], ], [ 'name' => 'THB', 'data' => [2, 3, 7, 6], ], ], 'credits' => ['enabled' => true], ] ]);
Output of the Json Reponse:
[{"name":"CN","data":[55,22,3,14]},{"name":"ID","data":[12,53,7,16]},{"name":"THB","data":[22,13,7,26]}]
Error I got:
VM21255:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at Object.success ((index):234) at fire (jquery.js:3187) at Object.fireWith [as resolveWith] (jquery.js:3317) at done (jquery.js:8757) at XMLHttpRequest.<anonymous> (jquery.js:9123)
@owliber, you're commenting on a closed issue. In short, it looks like you don't need the JSON.parse()
since data
should already be an object. Please open a separate issue if you have further questions.
I want to auto update highcharts with ajax using yii2-highcharts,I search and get these codes:
I want to know how to use it in yii2-highcarts? Can somebody give me a hints? thank you.