morrisjs / morris.js

Pretty time-series line graphs
http://morrisjs.github.com/morris.js/
6.92k stars 1.23k forks source link

How to automatically refresh chart without reloading the whole page? #706

Open Synthacon opened 7 years ago

Synthacon commented 7 years ago

Hi, I'm not sure is this the right place to ask this question but here it goes. I'm charting data retrieved from SQL. I also import data from php file to be able to refresh values without refreshing the whole page. Now I can see the chart with the data, but so far I had no luck making chart to auto refresh when new data is obtained (php refresh without reloading the page). After two days of reading forums and trying different approaches I'm totally out of ideas.

I would really appreciate your help on solving this problem.

My code:

...
$result = $conn->query($sql);
$result_array = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        //echo "id: " . $row["idusd"]. " - Name: " . $row["datenow"]. " " . $row["usd"]. "<br>";
        $result_array[] = $row;
    }
} else {
    echo "0 results";
}
$conn->close();
?>

<script>
      function auto_load(){
          $.ajax({
          url: "test.php",
          type: "GET", 
          cache: false}
               ).done(function(html) {
                 var divs = html.split('|');
                $( '#info-orders').html( divs[0] );
                $( '#info-usd').html( divs[1] );
                $( '#info-btc').html( divs[2] );
                $( '#info-ltc').html( divs[3] );
                $( '#info-nvc').html( divs[4] );
     });
  chart.setData(<?php echo json_encode($result_array); ?>); // this should redraw the chart

 }
 setInterval(auto_load,30000);
 </script>

 <script>
var chart = Morris.Line({
                  element: 'graph',
                  data: <?php echo json_encode($result_array); ?>, 
                  xkey: ['datenow'],
                  ykeys: ['usd'],
                  labels: ['Value'],
                  ymin: min(<?php echo json_encode($result_array); ?>),
                  barSizeRatio: 1,
                 pointSize: 1,
                 hideHover: 'auto',
                 gridIntegers: true,
});
function min(json_data) {
    var min = Number.MAX_VALUE;
    var max = Number.MIN_VALUE;
    for (var data_key in json_data) {
        var entry = json_data[data_key]
        for(var key in entry) {
            var x = entry[key];
            if (!isNaN(x)) { // to avoid using date object
                if (x < min) {min = x;}
                else if (x > max) {max = x;}
            }
        }
    }
    return min;
}
 </script>
TorosyanV commented 7 years ago

Maybe you need get data via ajax request?

gabrielbratescu commented 7 years ago

chart.setData should receive an object received from the ajax call, not from PHP. Something like chart.setData(html.data)