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.