Question

I'm trying to do a simple visualisation of some data from the database, which I get via JSON from a simple web service. Everything is done on localhost. The problem seems to be the JSON format for DataTable constructor. I have read the documentation and I think I have created the exact json format, but for some reason, when I pass the data to the DataTable constructor, it doesn't create the datatable, and the chart isn't initalized it just gives an error: Table has no columns. The data I get from the database are fine. The chart works with example data that is given as a literal, so it's not something with javascript.

Here is the code for the json generation(note, I've also tried to make json with the placment of "" and '' in reversed order, meaning 'cols': [{id: 'ID', type: 'string'}, and it doesn't work either):

$niz =  array();
while ($red = $db->getResult()->fetch_object())
{
    $niz[] = $red;
}

$jsonResponse = '{
    "cols": [{id: "ID", type: "string"},
    {id: "Poles", type: "number"},
    {id: "Victories", type: "number"},
    {id: "Team", type: "string"}
    ],
    "rows": [';

    $i = 0;
    foreach ($niz as $line) {
        $i = $i+1;
        $addOn = '{"c":[{"v": "'.$line->name.'"}, {"v": '.$line->poles.'}, {"v": '.$line->victories.'}, {"v": "'.$line->teamName.'"}]}';
        if($i == count($niz))
        {
            $addOn.='] }';

        }
        else
        {
            $addOn.=',';
        }
        $jsonResponse.=$addOn;
    }


    echo json_encode($jsonResponse);





});

And here is the code on the client side for the chart:

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript"  src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {

var jsonData = $.ajax({
url: "http://127.0.0.1/VisualisationWS/poleVictoryRatio.json",
dataType:"json",
async: false
}).responseText;

var data = new google.visualization.DataTable(jsonData);


var options = {
title: 'Correlation between pole positions and wins of drivers, taking in account the  team they are currently in.',
hAxis: {title: 'Poles'},
vAxis: {title: 'Victories'},
bubble: {textStyle: {fontSize: 11}},
};

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

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

Solution

Your JSON is invalid. Object keys in JSON must be quoted with double-quotes, eg: {id: "ID", type: "string"} should be {"id":"ID","type":"string"}. By manually encoding your data as JSON, you are missing out on all the benefits of having the json_encode function available to you (it actually does next to nothing in your current setup). If you construct your data in arrays, json_encode will happily take care of the tedious parts of encoding your data for you:

$myData = array(
    'cols' => array(
        array('id' => 'ID', 'type' => 'string'),
        array('id' => 'Poles', 'type' => 'number'),
        array('id' => 'Victories', 'type' => 'number'),
        array('id' => 'Team', 'type' => 'string')
    ),
    'rows' => array();
);
while ($red = $db->getResult()->fetch_object()) {
    $myData['rows'][] = array('c' => array(
        array('v' => $red->name),
        array('v' => $red->poles),
        array('v' => $red->victories),
        array('v' => $red->teamName)
    ));
}
echo json_encode($myData, JSON_NUMERIC_CHECK);

For reference, PHP's associative arrays are encoded as javascript objects, non-associative arrays are encoded as javascript arrays. JSON_NUMERIC_CHECK scans the data for numbers to make sure they are encoded as numbers and not strings (this helps because some databases will output numbers as strings, MySQL being the primary culprit).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top