Elvy Collado
Elvy Collado

Reputation: 39

Google Chart Area is not displaying mysql database

I am working with a raspberry pi3 lamp server to displaying the data from one AM2302 sensor. I have one php file that reads the value from the sensor and show it in json format.

I need help about how to display the historical data with the google area chart, the data is read from a python program and storage every one minute into a mysql database.

here is the file that read the data is called: read_sensors.php (the one that collects the data from the sensor).

<?php
// Settings
// host, user and password settings
$host = "localhost";
$user = "logger";
$password = "password";
$database = "temperatures";

// make connection to database
$connectdb = mysqli_connect($host,$user,$password)
or die ("Cannot reach database");

// select db
mysqli_select_db($connectdb,$database)
or die ("Cannot select database");

// sql command that selects all entires from current time and X hours backward
$sql= "SELECT temperature, humidity, sensor, dateandtime FROM temperaturedata where sensor = 'Exterior' order by dateandtime desc LIMIT 10";

// set query to variable
$temperatures = mysqli_query($connectdb,$sql);

// create content to web page
?>

<?php
// loop all the results that were read from database and "draw" to web page

$temps = [];
while($temperature = mysqli_fetch_assoc($temperatures)) {
    $temps[] = $temperature;
}

echo json_encode($temps);;
?>

It show me the following result:

[
    {"temperature":"26.8","humidity":"82.2","sensor":"Exterior","dateandtime":"2019-03-11 09:21:02"},
    {"temperature":"26.8","humidity":"83.7","sensor":"Exterior","dateandtime":"2019-03-11 09:20:01"},
    {"temperature":"26.8","humidity":"82.8","sensor":"Exterior","dateandtime":"2019-03-11 09:19:01"},
    {"temperature":"26.8","humidity":"82.7","sensor":"Exterior","dateandtime":"2019-03-11 09:18:01"},
    {"temperature":"27","humidity":"82.6","sensor":"Exterior","dateandtime":"2019-03-11 09:17:01"},
    {"temperature":"27.2","humidity":"83","sensor":"Exterior","dateandtime":"2019-03-11 09:16:02"},
    {"temperature":"27.2","humidity":"83.1","sensor":"Exterior","dateandtime":"2019-03-11 09:15:01"},
    {"temperature":"27.1","humidity":"82.8","sensor":"Exterior","dateandtime":"2019-03-11 09:14:02"},
    {"temperature":"27.1","humidity":"82.9","sensor":"Exterior","dateandtime":"2019-03-11 09:13:01"},
    {"temperature":"27","humidity":"82.8","sensor":"Exterior","dateandtime":"2019-03-11 09:12:01"}
]

here is the code for my index.php file:

<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src =
"https://www.gstatic.com/charts/loader.js">
      </script>

      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});
      </script>
   </head>

   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.

var dataArea = new google.visualization.DataTable();
dataArea.addColumn('string', 'Date');
dataArea.addColumn('number', 'Temperature');
dataArea.addColumn('number', 'Humidity');

var options = {title: 'Company Performance',
               hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
               vAxis: {minValue: 0}
            };

$.ajax({
  url: "read_sensors.php",
  dataType: 'json'
}).done(function (data) {
  $.each(data, function (index, row) {
    dataArea.addRow([
      row.dateandtime,
      parseFloat(row.temperature),
      parseFloat(row.humidity)
    ]);
  });
});


var chartArea = new
google.visualization.AreaChart(document.getElementById("chart_area"));

chartArea.draw(dataArea);

}
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>

At these moment when I access the index.php the page shows in blank (nothing)

here is the code with the mod.:

<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://www.gstatic.com/charts/loader.js"></script>
      </script>
      <script type = "text/javascript">
      </script>
   </head>

   <body>
      <div id = "chart_area" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.

var dataArea = new google.visualization.DataTable();
dataArea.addColumn('string', 'Date');
dataArea.addColumn('number', 'Temperature');
dataArea.addColumn('number', 'Humidity');

var options = {title: 'Company Performance',
               hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
               vAxis: {minValue: 0}
            };


$.ajax({
  url: "read_sensors.php",
  dataType: 'json',
}).done(function (data) {
  complete: function(data) {
    $.each(data, function(index, row) {
      dataArea.addRow([
        row.dateandtime,
        parseFloat(row.temperature),
        parseFloat(row.humidity)
      ]);
    });
    var chartArea = new google.visualization.AreaChart(document.getElementById("chart_area"));
    chartArea.draw(dataArea);
  }
});

}
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>

Upvotes: 1

Views: 301

Answers (2)

WhiteHat
WhiteHat

Reputation: 61222

the chart is being drawn before the data has been added.

move the chart draw code into the ajax done callback...

$.ajax({
  url: "read_sensors.php",
  dataType: 'json'
}).done(function (data) {
  $.each(data, function (index, row) {
    dataArea.addRow([
      row.dateandtime,
      parseFloat(row.temperature),
      parseFloat(row.humidity)
    ]);
  });

  var chartArea = new
  google.visualization.AreaChart(document.getElementById("chart_area"));

  chartArea.draw(dataArea, options);
});

also, the id of the <div> element needs to match the id given to the chart.

change the id to "chart_area", here...

  <div id="chart_area" style="width: 550px; height: 400px; margin: 0 auto">
  </div>

you may also need to move the load statement to the same section as the callback...

google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);

also need to add jquery to the page, you can add above the google charts library...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>

following are the suggested edits...

<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://www.gstatic.com/charts/loader.js"></script>
   </head>

   <body>
      <div id="chart_area" style="width: 550px; height: 400px; margin: 0 auto"></div>
      <script>
        function drawChart() {
          var dataArea = new google.visualization.DataTable();
          dataArea.addColumn('string', 'Date');
          dataArea.addColumn('number', 'Temperature');
          dataArea.addColumn('number', 'Humidity');

          var options = {
            title: 'Company Performance',
            hAxis: {
              title: 'Year',
              titleTextStyle: {color: '#333'}
            },
            vAxis: {minValue: 0}
          };

          $.ajax({
            url: "read_sensors.php",
            dataType: 'json',
          }).done(function (data) {
            $.each(data, function(index, row) {
              dataArea.addRow([
                row.dateandtime,
                parseFloat(row.temperature),
                parseFloat(row.humidity)
              ]);
            });
            var chartArea = new google.visualization.AreaChart(document.getElementById("chart_area"));
            chartArea.draw(dataArea);
          });
        }
        google.charts.load('current', {packages: ['corechart']});
        google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>

Upvotes: 2

Malekai
Malekai

Reputation: 5011

You should try using the complete option instead of done, for jQuery.ajax:

$.ajax({
  url: "read_sensors.php",
  dataType: 'json',
  // NOTE: callback for $.ajax.done(...) goes here
  complete: function(data) {
    $.each(data, function(index, row) {
      dataArea.addRow([
        row.dateandtime,
        parseFloat(row.temperature),
        parseFloat(row.humidity)
      ]);
    });
    var chartArea = new google.visualization.AreaChart(document.getElementById("chart_area"));
    chartArea.draw(dataArea);
  }
});

If that doesn't work you should check your CSS (inline or otherwise) for any display: none, or maybe your JavaScript for hide / fadeOut / slideDown.

If that doesn't work and you're using jQuery 2 (or 3) you should use jQuery.when.

For example:

$.when(function() {
  // code that you need to wait for
}).done(function() {
  // code that runs after code above is done
});

Good luck.

Upvotes: 0

Related Questions