2

I am trying to use Google Charts and populate it using external JSON file, which I have created in PHP via json_encode().

So I got google charts working, with static random data from example, which is:

function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Time', 'Temperature', 'Humidty'],
      ['2018-03-09 13:28:49',  1000,      400],
      ['2018-03-09 13:28:59',  1170,      460],
      ['2018-03-09 14:28:49',  660,       1120],
      ['2018-03-09 17:28:49',  1030,      540],
      ['2018-03-09 13:28:49',  1030,      540]
    ]);

So basically as I understand var data should be replaced with entries from my JSON file, which is formatted in the following manner:

[{"id":"1","temp":"24.40","hum":"28.30","insert_date":"2018-03-09 13:28:49"},{"id":"2","temp":"24.50","hum":"28.60","insert_date":"2018-03-09 13:29:59"}]

So the data I need would be temp, hum and insert date. So, the question is how do I parse it?

I've been trying for hours and haven't been able to figure it out.

Thanks

1
  • What do you mean by parse it? How are you getting the JSON? Is it coming in as a string? Commented Mar 22, 2018 at 8:28

3 Answers 3

1

recommend using ajax to get data from php

to create a google data table directly from json,
the json must be in a specific format, see...
Format of the Constructor's JavaScript Literal data Parameter

google.visualization.arrayToDataTable will not work with the json sample you posted
but, you can parse the json manually, row by row...

$.each(jsonData, function (index, row) {
  data.addRow([
    new Date(row.insert_date),
    parseFloat(row.temp),
    parseFloat(row.hum)
  ]);
});

recommend using the following setup...

google.charts.load will wait for the page to load,
no need for --> $(document).ready -- or similar function

once google loads, create the chart and data table,
these only need to be created once

then use ajax to get the data, and draw the chart

if you want to continuously add more data to the same chart,
wait for the chart's 'ready' event, then get more data

see following working snippet,
for example purposes, the sample data you provided is used in the ajax fail callback,
which can be removed...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  // create chart
  var container = $('#chart_div').get(0);
  var chart = new google.visualization.LineChart(container);
  var options = {
    chartArea: {
      height: '100%',
      width: '100%',
      top: 60,
      left: 60,
      right: 60,
      bottom: 60
    },
    hAxis: {
      format: 'M/d HH:mm:ss',
      title: 'Time'
    },
    height: '100%',
    legend: {
      position: 'top'
    },
    width: '100%'
  };

  // create data table
  var data = new google.visualization.DataTable();
  data.addColumn('datetime', 'x');
  data.addColumn('number', 'Temperature');
  data.addColumn('number', 'Humidity');

  // after the chart draws, wait 60 seconds, get more data
  google.visualization.events.addListener(chart, 'ready', function () {
    window.setTimeout(getData, 60000);
  });

  getData();
  function getData() {
    $.ajax({
      url: 'data.php',
      dataType: 'json'
    }).done(function (jsonData) {
      loadData(jsonData);
    }).fail(function (jqXHR, textStatus, errorThrown) {
      var jsonData = [{"id":"1","temp":"24.40","hum":"28.30","insert_date":"2018-03-09 13:28:49"},{"id":"2","temp":"24.50","hum":"28.60","insert_date":"2018-03-09 13:29:59"},{"id":"2","temp":"24.50","hum":"28.60","insert_date":"2018-03-09 13:31:10"}];
      loadData(jsonData);
    });
  }

  function loadData(jsonData) {
    // load json data
    $.each(jsonData, function (index, row) {
      data.addRow([
        new Date(row.insert_date),
        parseFloat(row.temp),
        parseFloat(row.hum)
      ]);
    });
    drawChart();
  }

  $(window).resize(drawChart);
  function drawChart() {
    // draw chart
    chart.draw(data, options);
  }
});
html, body {
  height: 100%;
  margin: 0px 0px 0px 0px;
  overflow: hidden;
  padding: 0px 0px 0px 0px;
}

.chart {
  height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="chart" id="chart_div"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Super helpful. Thanks, will try to get it working now!
0

In your page at bottom just initialize data to javascript variable and use it in chart function but note it drawChart() or file having this function should be included after that variable. Example is as bellow:

<script>
var php_data = "<?=$json_data?>";
function drawChart() {
    var data = google.visualization.arrayToDataTable(php_data);
</script>

an other solution is to pass data to drawchart function as variable like bellow:

<script>
var php_data = "<?=$json_data?>";
function drawChart(php_data) {
    var data = google.visualization.arrayToDataTable(php_data);
</script>

3 Comments

Thanks, hmm thing is that all the data is in a seperate file called data.php. which basically selects data from mysql and then json_encode()'s it. But there's some stuff like "id" in json I wont need :/
You can get it by including that file data.php or get data using ajax call and then assign it to javascript veriable
one other thing you can do is that send ajax call to data.php in start of drawChart() function to get json data from php file
0

I am aready created my json file, so I read frm ajax like this

function setSensor(sensor)
{
    $.ajax({
        url:"QueryPHPFile.php",
        method:'POST',
        data: {varData: data},
        beforeSend: function(){}
    }).done(function(res){
        res = JSON.parse(res);
        google.charts.load('current', {packages: ['corechart', 'line']});
        google.charts.setOnLoadCallback(function() {muestra2(res); });  

    }).fail(function(){
    }).always(function(){});
}

and then I have function muestra2 like this where res is also my json file

function muestra2(res)
    {
        // console.log(res);
        var data = null;
        data = new google.visualization.DataTable();
        data.addColumn('date', 'hAxis');
        data.addColumn('number', 'vAxis');
        var total = [];
        var ValueFloat;
        for (var i = res.length - 1; i >= 0; i--) {
            ValueFloat = parseFloat(res[i] ['NameLabelInYourJsonFile']); 
            var date2= res[i]['Fecha'];
            var esplit = date2.split("-",3);  //Format to date separated
            total.push([ new Date (esplit[0] , esplit[1] -1, esplit[2]),lecturaConvertida]); // new Date( , , )
        }

        data.addRows(total);

        var options = {
            hAxis: {
                title: 'hAxis Name',
                format: 'd MMM' 
                },
            vAxis: {
                title: 'vAxis Name'
                },
                backgroundColor: '#ffffff', //fondo de la grafica
                width: 700,
                lineWidth: 1, 
                height: 400,
                title: 'Name Graphic',

            };
        var chart = new google.visualization.LineChart(document.getElementById('line-chart'));
        chart.draw(data, options);
        }

with the res.lenght we know hoy record are in the Json File. For date you must use insert with newData, looking for more about this in the documentation, i hope this help you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.