Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format not being correct, but I'm struggling to determine the necessary format and how to modify my script to generate JSON accordingly.

The PHP script provided below is responsible for generating JSON data from the database:

<?php
require_once ("config.php");

$array = array();
$res = mysqli_query($con, "SELECT * FROM sensors WHERE vera_variable='CurrentTemperature'");
while ($row = mysqli_fetch_array($res)) {
    $sensor_id = $row['sensor_id'];
    $sensor_name = $row['sensor_name'];

    $res2 = mysqli_query($con, "SELECT * FROM logs WHERE sensor_id='$sensor_id'");
    while ($row2 = mysqli_fetch_array($res2)) {
        $time = strtotime($row2['log_time']);
        $formattedTime = date("m-d-y g:i", $time);

        $sensor_value = $row2['sensor_value'];

            $array[$formattedTime][$sensor_name] = $sensor_value;
    }
}

$json = json_encode($array,  JSON_PRETTY_PRINT);
echo "<pre>" . $json . "</pre>";

?>

An example output of the script includes a date, multiple sensors, and their corresponding values.

{
    "12-12-15 8:35": {
        "Living Room Temperature": "18.3",
        "Outside Temperature": "-5",
        "Mud Room Temperature": "16.0",
        "Basement Temperature": "14.0"
    },
    // additional data entries...
}

Beyond this point is a simple example chart using JSON:

<html>
    <head>
        <script language="javascript" type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

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

            function drawChart() {
                var jsonData = $.ajax({
                    url : "json_temp.php",
                    dataType : "json",
                    async : false
                }).responseText;

                var obj = window.JSON.stringify(jsonData);
                var data = google.visualization.arrayToDataTable(obj);

                var options = {
                    title : 'Graph'
                };

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

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

Upon trying to load the graph, Chrome displays the following error message:

Uncaught Error: Not an arraylha @ format+en,default+en,ui+en,corechart+en.I.js:191bha @ format+en,default+en,ui+en,corechart+en.I.js:193drawChart @ temperature.php:22

Answer №1

This issue arises because the input JSON data format (obj variable) does not align with the required Google Chart data JSON format.

To resolve this, you can convert the input data to the corrected format by following the example below:

var chartData = [];
chartData.push(['Time','Living Room Temperature','Outside Temperature','Mud Room Temperature','Basement Temperature']);
for (var key in obj) {
     var item = obj[key];
     chartData.push([new Date(key),parseFloat(item['Living Room Temperature']),parseFloat(item['Outside Temperature']),parseFloat(item['Mud Room Temperature']),parseFloat(item['Basement Temperature'])]);       
 }
 var data = google.visualization.arrayToDataTable(chartData);

Example in action

Modifications have been implemented on how the data is retrieved, as synchronous calls are discouraged and replaced with async: true. Moreover, requests now utilize promises.

google.load("visualization", "1", {
    packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);

function drawChart() {
    $.ajax({
        url: "https://gist.githubusercontent.com/vgrem/e08a3da68a5db5e934a1/raw/2f971a9d1524d0457a6aae4df861dc5f0af0a2ef/data.json", //json_temp.php
        dataType: "json"
    })
    .done(function (data) {
        
            var chartData = [];
            chartData.push(['Time','Living Room Temperature','Outside Temperature','Mud Room Temperature','Basement Temperature']);
            for (var key in data) {
                var item = data[key];
                chartData.push([new Date(key),parseFloat(item['Living Room Temperature']),parseFloat(item['Outside Temperature']),parseFloat(item['Mud Room Temperature']),parseFloat(item['Basement Temperature'])]);       
            }

            var dataTable = google.visualization.arrayToDataTable(chartData);
            var options = {
                title: 'Graph'
            };
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(dataTable, options);

     });
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

Answer №2

It appears that you're passing an Object instead of the expected Array.

Here's an alternative approach:

let obj = JSON.stringify(jsonData);
let arr = [];
Object.keys(obj).forEach(function(key){
   let o = obj[key]; 
   o.time = key; 
   arr.push(o);
});
let data = google.visualization.arrayToDataTable(arr);

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

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

Passing a range to the search model in Yii2: A step-by-step guide

How can I search within a specific range for a field using the Search Model? Is there a way to implement between, greater than, or less than statements in the search model? I have attempted something like this, but it seems that these attributes are not v ...

router.query is returning an empty object when using Next.js

Here is how my folders are organized: https://i.stack.imgur.com/TfBtv.png In addition, here is a snippet of my code: const router = useRouter(); const { id } = router.query; The issue I'm facing is that the id is returning {} instead of the actual ...

Enhancing nouislider jQuery slider with tick marks

I have integrated the noUIslider plugin () into one of my projects. I am seeking guidance on how to display tick marks below each value on the slider. This is the current initialization code for the slider: $slider.noUiSlider({ 'start': sta ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

Learn the process of transferring information from a dynamically generated table to a database using PHP

After creating a table using PHP dynamically, I am facing an issue with updating some cell values based on user input. I have provided my code below. I tried using [] in the names attribute to make names an array as suggested on Stack Overflow, but it didn ...

What is the method for React to tap into the local variables of Hooks functions?

Here we have a basic hook example function App() { let [counter, setCounter] = useState(0); return <button onClick={() => setCounter(counter + 1)}>{counter}</button>; } My understanding of React operation is: React will invoke App() to ...

Perform a count operation in mySQL for a specific selection criteria

Hi there, Consider the scenario where I have the following Select statement in mySQL: $select_query = "SELECT filename FROM files WHERE file_id='$file_id'"; $query_result = mysql_query($select_query); $file_info = mysql_fetch_array($query_result ...

The compilation of PKG using Axios 1.x encounters an error

Despite attempting numerous strategies, I have not been successful. I developed a Node.js application with API requests managed using axios. However, I am unable to convert it into an executable file. Trying to downgrade Axios to version 0.27.0 resolved th ...

Transforming a collection of Plain Old Java Objects into JSON will solely display the "id" attributes

I encountered an unusual issue with my project setup. I created a REST endpoint by bootstrapping a mvn archetype using Jersey, Grizzly2, and Moxy. This endpoint is supposed to return a Set of all POJOs in the DataSource. However, when I make a @GET request ...

What is the best way to create a personalized image as the background in WordPress using CSS for a client?

I have this in my style.css .showcase{ background: url("x.jpg") no-repeat 0; } My website is built on WordPress and I have implemented advanced custom fields for the client to edit text. However, I am struggling to find a way for them to change the ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

Cross-platform mobile browsers typically have scrollbars in their scrollable divs

I have successfully implemented scrollable div's on a page designed for tablets running Android 3.2+, BlackBerry Playbook, and iOS5+ (except iPad 1). However, I would like to add scrollbars to improve the user experience. For iOS5, I can use the suppo ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Creating a stylish button using a combination of CSS and Javascript classes within a webpage layout

Is it feasible to include a button in the layout that has HTML, CSS styles, and JavaScript functionality? For instance: This button is designed with both CSS styling and JavaScript classes. How can one incorporate CSS and JavaScript along with HTML conte ...

Guiding Users from Outdated PHP URLs with Django Redirects

Essentially, my goal is to achieve the following: urlpatterns = patterns('', url(r'^old/site/url.php?someshit=(?P<id>\d+)', 'website.views.redirect_php'), ) However, I keep encountering a 404 error.. ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...