Utilize the Google Chart API alongside JSON in order to generate a visually appealing line chart based

I am currently attempting to generate a line chart using the Google Chart API by setting data with JSON for the datatable through AJAX post requests.

Although I have successfully implemented this method for a pie chart, I am struggling to replicate it for a line chart.

Below is my code snippet for creating the chart with an AJAX post request:

function drawLineGraph()
             {
                 $.post("loadGraph.php",
                    {
                        type: "line"
                    },
                    function (result)
                    {
                        var data = new google.visualization.DataTable(result);
                        var options = {
                            title: "Line Graph Test"
                        };

                        var chart = new google.visualization.LineChart(document.getElementById("lineChart"));
                        chart.draw(data, options);
                    }, "json"
                );
             }

Here is the PHP code for loadGraph.php:

print json_encode(test());

    function test()
    {
        $array = array();
        if ($_POST['type'] == "line")
        {
            $array['cols'][] = array('type' => 'string');
            $array['cols'][] = array('type' => 'number');

            $temp = array();
            $array['row'][] = array('v' => (string) "20-01-13");
            $array['row'][] = array('v' => (int) 35);
            $array['row'][] = array('v' => (string) "21-01-13");
            $array['row'][] = array('v' => (int) 30);

        }
}

Even though no errors are thrown, the line chart does not display correctly - it appears empty. Below is a screenshot of the issue.

The following is the JSON output:

{"cols":[{"type":"string"},{"type":"number"}],"row":[{"c":[{"v":"20-01-13"},{"v":22}]},{"c":[{"v":"21-01-13"},{"v":24}]},{"c":[{"v":"22-01-13"},{"v":27}]}]}

Your assistance in resolving this matter is greatly appreciated.

UPDATE I attempted @davidkonrad's solution but encountered a new problem. By changing 'row' to 'rows' in the PHP array:

    $array['cols'][] = array('type' => 'string');
    $array['cols'][] = array('type' => 'number');

    $array['rows'][] = array('c' => "20-01-13");
    $array['rows'][] = array('v' => 35);
    $array['rows'][] = array('c' => "21-01-13");
    $array['rows'][] = array('v' => 30);

Upon loading the graph, a

Cannot read property '0' of undefined
error is displayed instead of the chart. Here is the updated JSON structure:

{"cols":[{"type":"string"},{"type":"number"}],"rows":[{"c":"20-01-13"},{"v":35},{"c":"21-01-13"},{"v":30}]}

I am unable to determine how to adjust the array to align with davidkonrad's suggested JSON format.

Answer №1

There seems to be a minor typo issue in the JSON data. Instead of using row, it should be specified as rows.

For example, if we update the JSON data like this:

var result = { "cols":[ {"type":"string"}, {"type":"number"}], "rows":[ {"c":[{"v":"20-01-13"}, {"v":22}]}, {"c":[{"v":"21-01-13"}, {"v":24}]}, {"c":[{"v":"22-01-13"}, {"v":27}]} ]};

the code will work properly :

Update

Refer to Format of the Constructor's JavaScript Literal data Parameter Each "c"-section needs to be wrapped in brackets and the "v" (value indicator) for the first column is missing.

The corrected test JSON would be

"cols": [
    {"type":"string"},{"type":"number"}
        ],
"rows":[
    {"c":"20-01-13"},{"v":35},
    {"c":"21-01-13"},{"v":30}
        ]
}

resulting in an error "can't read 0 of undefined", so it should actually be

{
"cols":[
    {"type":"string"},{"type":"number"}
    ],
"rows":[
    {"c": [{ "v": "20-01-13"},{"v":35} ]},
    {"c": [{ "v": "21-01-13"},{"v":30} ]}
    ]
}

graph :

I hope this clarification helps!

Absolutely final update

The PHP has been modified alongside json_encode to output data in the correct format for Google charts :

function test() {
    $array = array();

    $array['cols'][] = array('type' => 'string');
    $array['cols'][] = array('type' => 'number');

    //Here is the crucial difference
    $array['rows'][]['c'] = array(
        array('v' => "20-01-13"),
        array('v' => 35)
    );
    $array['rows'][]['c'] = array(
        array('v' => "21-01-13"),
        array('v' => 30)
    );

    return json_encode($array);
}

This will output

{"cols":[{"type":"string"},{"type":"number"}],"rows":[{"c":[{"v":"20-01-13"},{"v":35}]},{"c":[{"v":"21-01-13"},{"v":30}]}]}

which aligns with the graph mentioned above

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

The process of deleting lines from an image using Javascript

If I have an image of a data-table and I want to eliminate all the grid lines (defined as continuous vertical or horizontal pixels), is there a way to achieve this using Javascript's image data manipulation? I envision looping through a 2D array conta ...

Can you provide the regular expression that will reject the character "?"

Can you help me verify that my form does not accept double quotes? Validators.pattern(/^(?!").*/g) The current solution is not functioning properly. I want to allow all characters except for double quotes. ...

React.js - Error message: onChange is not defined

My application has successfully integrated the last.fm API to fetch related artists. The concept is simple - search for an artist and receive a list of related artists in return. While using 'onClick' works flawlessly as it retrieves the input v ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

What is the process of serializing a JBox2d World object?

My server has multiple clients connecting, each controlling a player body. Collisions can occur, so players need to see other bodies to understand movement restrictions. To achieve this, I transmit the "World" object using object streams and parse and dra ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Is there a way to obtain a non-matching string in JavaScript?

I have an array of bookings and need to search for a specific value inside the array using searchValue. In this case, I need to check the booking id field. If the booking id matches the searchValue, then I need to push that object into the result array. ...

The process of creating a React build varies greatly from the initial development phase

Thank you for offering to help me! After building my React web app, it looks very different from development mode. I use serve -s build to monitor the app build. However, even on my online DigitalOcean server, it doesn't appear the same as in develop ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

Prevent submission of angularjs form when image exceeds size limit

Here is a form with custom file upload functionality: <div class="form-group"> <input type="file" id="files" file-upload="myFile" ng-disabled="isBig" class="form-control" name="files" /> <output id="list"></output> </div> ...

Issues encountered when trying to execute npm start: "The function this.htmlWebpackPlugin.getHooks is not recognized."

My background in web development is weak, and I'm facing a challenging situation. I had to take over the work of a colleague who left, and now I'm trying to finish the site we were working on. Since then, I've been learning about web develop ...

Problem Encountered with Jquery Validation for Name Field (Restriction to Alphabetic

I am struggling to validate a name format using a predefined jQuery validation tool. My intention is for the name field to accept only characters, but even with the correct regex pattern, it still allows numbers to be entered. The specific script I am us ...

Implementing sound playback within an AJAX response

Recently, I implemented a jQuery code to automatically refresh a specific div. This auto-refresh feature uses AJAX to generate notifications whenever there is a new request from a client, similar to social network notifications. I even incorporated music f ...

Converting an array of strings to integers using Highcharts and JavaScript

Trying to create a chart using highcharts involves getting data from a datatable in VB.NET, converting it into an array, then transforming it into JSON before passing it back to JavaScript for rendering. However, the data is not appearing on the chart, pos ...

Tips for dynamically swapping out a texture image on a 3D model in three.js using Maya runtime

This website is currently loading a Maya model using the three.js library. The model includes various texture pictures. Below is the JavaScript code: var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container; var c ...

What steps can I take to stop Node.js from caching 'require' module executions?

After researching, I've come to understand that the require function automatically executes and parses the functions in the module. Is there a way to prevent this automatic execution? Here's the scenario: In order to avoid having an excessively ...

How to create a clickable link using Vuetify's v-btn component

As a newcomer to vue and vuetify, I would greatly appreciate some explanation and examples. My goal is to create a button that directs users to an external site, like youtube.com. Below is the code I currently have, but unfortunately it's not function ...

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

When a React page is re-rendered using useEffect, it automatically scrolls back to the

Every time I utilize the <Tabs> component, the onChange method triggers the handleTabChange function. This leads to the component being called again and after repainting, the useEffect is triggered causing the page to scroll back to the top. How can ...

JSON file parser that outputs the schema of a JSON file

Is there a way to showcase the schema of a JSON file in a tree structure format? I am looking for a JSON parser in C++ that can generate the schema of a JSON file. ...