Using Javascript, Google Charts is able to interpret JSON data

I am currently working on integrating Google Charts and populating it with data from an external JSON file that I have generated using PHP's json_encode() function.

After some effort, I managed to get Google Charts to display data successfully, but for now, I have hardcoded random values for demonstration purposes:

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]
    ]);

My ultimate goal is to replace this static data with entries from my JSON file structured like this:

[{"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"}]

The specific fields I want to extract are temperature, humidity, and insertion date. The challenge lies in parsing this data effectively.

I've been grappling with this issue for quite some time without success. Any guidance or suggestions would be greatly appreciated.

Thank you

Answer №1

Suggest utilizing ajax to fetch data from php

In order to generate a google data table directly from json,
the json needs to be in a specific format, refer to...
Format of the Constructor's JavaScript Literal data Parameter

google.visualization.arrayToDataTable
won't function with the json example provided by you
however, you can manually parse the json, row by row...

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

Recommend using the setup below...

google.charts.load will wait for the page to load,
no requirement 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 wish to continuously add more data to the same chart,
wait for the chart's 'ready' event, then obtain more data

view the working snippet below,
for illustration 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>

Answer №2

To display a chart on your webpage, you can initialize the data as a JavaScript variable at the bottom of your page and then use it in the chart function. However, make sure that drawChart() or the file containing this function is included after the variable declaration. Here is an example:

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

Another approach is to pass the data to the drawChart function as a parameter like this:

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

Answer №3

I have already created my JSON file, so I read from AJAX in this manner:

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() {displayGraphs(res); });  

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

Next, I have a function called displayGraphs where the variable "res" represents my JSON data:

function displayGraphs(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); 
            total.push([ new Date (esplit[0] , esplit[1] -1, esplit[2]),ValueFloat]); 
        }

        data.addRows(total);

        var options = {
            hAxis: {
                title: 'hAxis Name',
                format: 'd MMM' 
                },
            vAxis: {
                title: 'vAxis Name'
                },
                backgroundColor: '#ffffff', 
                width: 700,
                lineWidth: 1, 
                height: 400,
                title: 'Graph Title',

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

Using `res.length`, we can determine how many records are in the JSON file. When dealing with dates, make sure to insert newData as needed based on the documentation provided. Hope this explanation helps you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Appending a new element to a JSON object using JavaScript

Hey there, I have a JSON object called departments. When I use console.log(departments) it displays the following data: { _id: 58089a9c86337d1894ae1834, departmentName: 'Software Engineering', clientId: '57ff553e94542e1c2fd41d26', ...

The development of the React app will pause momentarily upon encountering a single low-severity vulnerability. To address this, you can either run `npm audit fix` to resolve it, or use `npm audit` to gain

A challenge arises while executing the command below in Visual Studio Code to develop a react app: create-react-app my-first-react-app The process halts and displays this message: found 1 low severity vulnerability run `npm audit fix` to rectify th ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

What is the best way to extract information from a JSON array using Gson?

Currently, I have obtained a json file with data structured in the following format: [ [ "name1", "age1", "gender1", url1 ], [ "name2", "age2", "gender2", url2 ], ... ] I am looking to parse this data and s ...

Troubleshooting issue with decoding encoded JSON in PHP

Below is the content of my data.php file: $global = $pdo->query("SELECT name, age"); $global = $global->fetchAll(PDO::FETCH_ASSOC); $arr = array('data'=>$global); echo json_encode($arr, JSON_PRETTY_PRINT); This is what my index.php ...

Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker ...

Is there a new update to Google Maps API?

After successfully building a map component for a web application using google maps, open layers, and the dojo toolkit, it suddenly stopped loading earlier this morning. Even though there are no JavaScript errors and open layers and Google still initialize ...

Find two separate solutions to the promise

I'm in the process of developing a promise-based route and here is my current promise implementation: const allowEdit = (postid, username) => { return new Promise((resolve) => { db.query(`SELECT * FROM post WHERE id = ${postid} AND usernam ...

Display an image using a modal window and Ajax XMLHttpRequest

I was tasked with creating a button that can load various types of content (text, images, videos, etc) into a modal popup window using Ajax without any frameworks. So far, I've been successful with text but have run into issues with loading images. De ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

Disabling Firebase error logging for unsuccessful signInWithEmailAndPassword attempts

My current project involves setting up a login system using Firebase auth in NextJS. Strangely, when I call the login function with incorrect credentials, an error is logged to the console even though my catch statement for handling errors is empty. Is the ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

What is the method for sending an AJAX request with a dynamically looping ID number parameter in the URL

I am looking to make multiple AJAX calls with a loop parameter named [id] in the URL, starting from request.php?id=1 and ending at id=9. I want to send each call after a 3-second delay. As a JavaScript beginner, I'm unsure of where to begin implementi ...

Combining Two DIVS Side by Side

Hey there, I am working on a timeline using two divs within a table cell. My goal is to have these divs overlap instead of appearing one below the other. The position attribute for all the DIVs inside the cell must remain unchanged due to the drag/drop fu ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

The File plugin in Ionic 3 is encountering difficulties in writing files on the device

I am developing an app using Ionic 3 and the file plugin. My goal is to write a JSON string to a JSON file located in my assets folder with the following hierarchy: assets -> mock -> msg-list.json , with "assets" as the main folder in the Ionic file ...

Using AJAX, retrieve the attribute of a button and assign it to a node

I'm currently facing a dilemma in trying to pass the name of a clicked button to my node server. I have this code snippet in Node.js: app.get('/someUrl', function(req, res) { console.log(req.body.name); }); Meanwhile, my jQuery/ajax ...

Check if the string contains any numerical characters

Is there a way to check if a string contains at least one numerical character without verifying if the entire string is a number? The current code works in the following situations: If there is a single integer, such as "43", it will display the correspon ...