javascriptphpjsonhighchartslive-update

dynamic chart with Highcharts using json


I've a question about how to create a dynamic chart using json, I tried and my graph didn't show a result, when I checked out, I've no error with my code. This is my code :

    <script>
    var chart; // global

    function requestData() {
        $.ajax({
            url: 'api_heartrate.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(eval(point), true, shift);

                // call it again after one second
                setTimeout(requestData, 1000);  
            },
            cache: false
        });
    }

    $(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: 'Value',
                    margin: 80
                }
            },
            series: [{
                name: 'Random data',
                data: []
            }]
        });     
    });
    </script>

</head>
<body>

    <div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>`

this is my json : http://health.barrukurniawan.tech/api_heartrate.php [{"time":"2018-08-02 09:30:11","nilai_sensor":"78"}]

I tried following a tutorial from this link : Highcharts Dynamic Chart with MySQL Data doesn't reload

Thanks for your attention, gladly waiting for an answer :)


Solution

  • There are multiple small errors in your approach

    1. eval is bad, parse it using JSON.parse instead.
    2. During load, chart is not defined yet, so your callback will not work.
    3. Highcharts needs time in milliseconds since 1970.
    4. highcharts expects an object {x: , y: ,...} you give it {time: , nilai_sensor: }.

    Solutions:

    1. point = JSON.parse(point)
    2. events: {
        load: function() {
          setInterval(function() {
            requestData(chart)
          }, 1000);
        }
      }
      
    3. new Date(point[0].time).getTime()
    4. {x: new Date(point[0].time).getTime(), y: point[0].nilai_sensor}

    Here is a working example using your input with static data(and some added time to keep it moving): https://jsfiddle.net/ewolden/md975oLk/23/