Search code examples
javascriptphpajaxgoogle-visualizationpartial-page-refresh

Google Line Chart - Refresh database automatically


I'm working on an interface which display data retrieved from my database thanks to a Google Line Chart. However, new data is stored in my database every 10 seconds and I can not refresh the chart automatically.

I need something really basic and I've already looked on the internet. I read something about Javascript/AJAX/JQuery ... but I'm more comfortable with Hardware :D

Here's my files EDIT : Chart_get and the main file have been modified according to @Michel answer.

fetch.php - Fetch the data and echo

<?php // Connection and Request stuff

  $host = blablabla
  (...)
  $req = $bdd->query('SELECT id, battery FROM Station');

  while ($data = $req->fetch()){
      $id = addslashes($data['id']);
      $charge_batt = intval($data['charge_batt']);
      $result .= "['".$id."' , ".$charge_batt."],";
  }

  $result = substr($result, 0, -1); // Erase the last ","
  echo $result;

?>

Output :

['1' , 90],['2' , 89],['3' , 80],['4' , 100],['5' , 90],['6' , 50],['7' , 67]

chart_get.php - Initialize the chart and draw it with the "echo $result" data

    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([    
<?php   
        echo ("['Date', 'Battery'],");
        include('fetch.php');
?>    
        ]);

        var options = {
          title: 'Battery health',
          animation:{
              duration: 1000,
              easing: 'out',
          },
          curveType: 'function'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }      
    </script>


    <div id="chart_div" style="width: 900px; height: 500px;"></div>

To refresh the "chart_div" I've tried :

main.html - jQuery script with load function

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>

            <title>Project - Chart</title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

        <script type="text/javascript" src="jQuery.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                // first load it once, so it display's the chart 
                $('#tableHolder').load('chart_get.php');
                // then execute the interval
                setInterval(function(){$('#tableHolder').load('chart_get.php');}, 5000);
                });
    </script>

    </head>

    <body>

        <p>Hello</p>
        <div id="tableHolder"> </div>

    </body>
</html>

But the chart is not displayed at all. I have absolutely no idea what I'm doing wrong. I am reading in a fast way some tutorials about javascript but if you know how to resolve my issue it would be great to help me :) Thanks !


Solution

  • Solution from OP.

    I've found the answer!

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
        <head>
    
                <title>Projet GreenFeed - Station de recharge a energie positive</title>
                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    
    
            <script type="text/javascript" src="https://www.google.com/jsapi"></script>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
            <script type="text/javascript">
    
            // Load the Visualization API and the piechart package.
            google.load('visualization', '1', {'packages':['corechart']});
    
            // Set a callback to run when the Google Visualization API is loaded.
            google.setOnLoadCallback(drawChart);
    
            function drawChart() {
    
    //AJAX Call is compulsory !
    
            var jsonData = $.ajax({
              url: "chart_fetch.php",
              dataType:"json",
              async: false
              }).responseText;
    
              // Create our data table out of JSON data loaded from server.
              var data = new google.visualization.DataTable(jsonData);
    
              var options = {
                   title: 'Battery',
                  is3D: 'true',
                  width: 800,
                  height: 600
                };
              // Instantiate and draw our chart, passing in some options.
              // Do not forget to check your div ID
              var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
              chart.draw(data, options);
            }
            </script>
    
    
            <script type="text/javascript" src="jQuery.js"></script>
            <script type="text/javascript">
    
                    $(document).ready(function(){
                        // First load the chart once 
                        drawChart();
                        // Set interval to call the drawChart again
                        setInterval(drawChart, 5000);
                        });
            </script>
    
        </head>
    
        <body>
    
            <div id="chart_div"> </div>
    
        </body>
    </html>