Retreiving php json data to a chart.

920 views
Skip to first unread message

apatuka

unread,
May 4, 2012, 3:31:56 PM5/4/12
to Google Visualization API
Hello everyone, im trying and it seems very painful the google api
with json.

Here is my code:

My php code:
<?php
$datos = array(
"cols" => array(
array("id"=>"dia", "label"=>"Dia", "type"=>"number"),
array("id"=>"juegos", "label"=>"Juegos", "type"=>"number"),
array("id"=>"programas", "label"=>"programas",
"type"=>"number")
),
"rows" => data(),
);
function data(){
$datos = array();
for($i=0;$i<10;$i++){
$datos[$i]=array("dia" => $i+1, "juegos" => rand(0,1000),
"programas" => rand(0,1000));
}
return $datos;
}
header('content-type: application/json');
echo json_encode($datos);
?>

my html

function drawChart() {
var jsonData = null;
var jsonDataRes = $.ajax({
url: "json_service.php",
dataType:"json",
async: false,
success: (
function(data) {
jsonData = data;
})
});

var data = google.visualization.arrayToDataTable(jsonData);

The error is "Not an array" on the firebug.

Any suggestions?

asgallant

unread,
May 7, 2012, 9:50:58 AM5/7/12
to google-visua...@googlegroups.com
You almost have it correct.  You started off building a (mostly complete) json DataTable, but then pass it to the #arrayToDataTable method.  What you should do is make a few small changes to the PHP side of things (to fix the json structure) and then pass the json directly to the DataTable constructor, like this:

<?php 
$datos = array( 
    "cols" => array( 
        array("id"=>"dia", "label"=>"Dia", "type"=>"number"), 
        array("id"=>"juegos", "label"=>"Juegos", "type"=>"number"), 
        array("id"=>"programas", "label"=>"programas", "type"=>"number") 
    ), 
    "rows" => data(), 
); 
function data(){ 
        $datos = array(); 
        for($i=0;$i<10;$i++){ 
                $datos[$i]=array('c' => array('v' => $i+1), array('v' => rand(0,1000)), array('v' => rand(0,1000))); 

        } 
        return $datos; 

        header('content-type: application/json'); 
        echo json_encode($datos); 
?> 

function drawChart() { 
    var jsonData = null; 
    var jsonDataRes = $.ajax({ 
        url: "json_service.php", 
        dataType:"json", 
        async: false, 
        success: (function(data) { 
            jsonData = data; 
        }) 
    }); 
    var data = new google.visualization.DataTable(jsonData);
//...
}


BTW, setting the AJAX request to synchronous (async: false) defeats the point of using AJAX.  If you move the chart drawing code inside the success handler function, then you can work asynchronously and enjoy all the benefits thereof.
Reply all
Reply to author
Forward
0 new messages