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

Enhancing Accessibility for the jQuery Countdown Plugin

Seeking to enhance the accessibility of my website's jQuery countdown, I am striving to adhere to WAI-ARIA guidelines. The specified requirements are as follows: Ensure the area is live so it updates dynamically with the countdown display. Avoid re ...

Battle of Kingdoms API ajax

When attempting to access Clash of Clans API information in this script, the following error is encountered: Refused to execute script from 'https://api.clashofclans.com/v1/leagues?authorization=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6Ij ...

jQuery GetJson fails to execute success function

I'm trying to use this code for an Ajax request to a JSON file: let formData = $("#myform").serialize(); $.getJSON("/files/data.json?" + formData, function(response){ alert(response); } ); However, there are no errors and the alert is n ...

Transferring data only once specific agreements have been fulfilled

Imagine having a file with specific promises that, when executed sequentially, create an input file called input.txt. // prepareInput.js var step1 = function() { var promise = new Promise(function(resolve, reject) { ... }); return p ...

How can I extract the id of a clicked item and pass it to a different page with Jquery?

Facing an issue where the attribute value of a clicked href tag is not retained after browser redirection. Initially, when clicking on the href tag, the value is displayed correctly. However, upon being redirected to the peoplegallery_album, the id becomes ...

Vuetify's scrolling list feature allows for smooth navigation through a list

Check out my Vuetify code snippet that utilizes a list: <v-list> <v-list-tile v-for="user in users" :key="user.id" avatar @click="" > <v-list-tile-content> < ...

Extracting information from JSON and presenting it in a structured table format

I've hit a wall with this JavaScript issue on my website. I'm trying to convert API JSON data into a table, and it's working fine when the data is on separate lines. However, when I introduce nested arrays in the JSON data, everything ends u ...

Leverage the power of v-model props in your Vue 3 component to efficiently retrieve API breakpoints

I am currently working on integrating the API breakpoints in my child component. These components are designed for my football web application. The breakpoints are sourced from: api-football My challenge lies in passing multiple prop values into a c ...

Javascript 'break' statement is always executed

It seems like I'm overlooking a very basic concept here. Why isn't my code reaching the else statement? The issue might be related to the break statement. It's likely something simple that I am missing. Code Snippet: <button onclick="yo ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

Run JavaScript code that is retrieved through an ajax request in Ruby on Rails

When I use Rails to render a javascript view, the code looks like this: $("##{@organization.id}-organization-introtext").hide(); $("##{@organization.id}-organization-full").append("#{escape_javascript(render @organization)}").hide().fadeIn('slow&apos ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Utilizing JSON for HTML conversion in Codeigniter

public function getCrew(){ $search = $this->input->post('name'); if($this->input->post('ajax') && (!empty($search))){ $result = $this->model->getNames($search); foreach($result as $r){ ...

Creating an onchange event in CodeIgniter for dynamically generated select boxes within a view script

As a beginner with codeigniter, I am seeking some assistance. Within my controller, I retrieve data for both options and suboptions, then load the respective view using the code below. The view essentially generates a table consisting of select boxes passe ...

Issue with accessing Scope value in AngularJS directive Scope

FIDDLE I've recently developed a directive that looks like this: return { restrict: 'EAC', scope: { statesActive: '=' }, link: function (scope, element, attrs) { var ...

Sending product identification to content_ids for Facebook Pixel tracking

Looking to implement Facebook Pixel for tracking the ViewContent event on product pages. According to Facebook, it's necessary to provide content_ids or contents along with a content_type. I assume that the content_type should always be 'product ...

Customizing the default settings of a d3 funnel chart

I recently used the following link to create a funnel chart using D3: jakezatecky/d3-funnel Everything was working perfectly. However, I wanted to adjust the block heights in proportion to their weight as mentioned in the tutorial by changing the D3 defau ...

Modifying text size using JavaScript string manipulation

I'm currently experimenting with a countdown script, but I'm struggling to change the size of the numbers displayed. Can anyone help me find where I can adjust the font and font size in this script? var eventdate = new Date("February 20, 2014 11 ...

What is the most effective way to update values in a JsonObject / JsonArray without using additional

If I have already converted a JSON String into a GSON provided JsonObject class (assuming I don't want to parse it into data objects and strictly want to use JsonObject), how can I directly modify a field/value of a key? I am unable to find an API th ...