issue with passing JSON array

1,994 views
Skip to first unread message

mkin...@gmail.com

unread,
Feb 20, 2014, 4:41:35 PM2/20/14
to google-visua...@googlegroups.com
Im trying to get the basic PHP example to work. 


This is what I want to work, but does not:
function drawChart() {
     
var jsonData = $.ajax({
          url
: "getData.php",
          dataType
:"json",
          async
: false
         
}).responseText;
         
     
// Create our data table out of JSON data loaded from server.
     
var data = new google.visualization.arrayToDataTable(jsonData);
my getData.php does some sql and parsing. If I do this instead, it works fine, just only once since its php instead of a jquery ajax call :

function drawChart() {
     
   
     
// Create our data table out of JSON data loaded from server.
     
var data = new google.visualization.arrayToDataTable( <?php include 'getData.php'; ?> )
If I do 
var jsonData = $.ajax({
          url: "getData.php",
          dataType:"json",
          async: false
          }).responseText;

document.write(jsonData);


      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.arrayToDataTable( PASTE STUFF HERE );
and then run it once to cut and paste the output into PASTE STUFF HERE then it works fine. If I actually use the jsonData variable as in the example, it does not work. What newb mistake am I making here?
 

asgallant

unread,
Feb 20, 2014, 5:38:50 PM2/20/14
to google-visua...@googlegroups.com
The responseText property of the AJAX call gives the string value of the returned data, which is not usable by the arrayToDataTable method.  Assuming jsonData is a valid JSON string for a javascript array, you need to call JSON.parse on jsonData:

var data = new google.visualization.arrayToDataTable(JSON.parse(jsonData));

mkin...@gmail.com

unread,
Feb 20, 2014, 5:50:50 PM2/20/14
to google-visua...@googlegroups.com
Tried that. No change. But it feels like the right direction to look in. That jquery code is exactly from the php example. The difference is it uses google.visualization.DataTable instead of arrayToDataTable. Is there a change to the jquery I need to make so it passes back whatever arrayToDataTable wants? Again worth noting that just sourcing the getData.php code instead of the jsonData variable name works fine. That just leads to the kludge of having to reload the whole page to refresh the chart.

I guess the other way to go is to add a bunch of extra code in getData.php to add all the extra quotes and commas and useless metadata and output a DataTable instead of an array. Just feels like pointless work.

asgallant

unread,
Feb 20, 2014, 6:25:43 PM2/20/14
to google-visua...@googlegroups.com
If your PHP is generating something like this:

{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}

then you need to use the regular DataTable constructor instead of the arrayToDataTable method:

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

If it is an array of data instead, you need to remove the "new" keyword from the line I posted previously:

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

mkin...@gmail.com

unread,
Feb 20, 2014, 6:33:34 PM2/20/14
to google-visua...@googlegroups.com
Same results. Ie, nothing.


getData.php outputs : [ ['Time','Temperature', 'Humidity'], ['2014-02-20 01:06:21',68.54,51.9],['2014-02-20 01:09:09',68.18,59.9],['2014-02-20 01:12:16',67.64,68.6],['2014-02-20 01:15:14',67.64,73.9],['2014-02-20 01:19:06',67.82,66.1],['2014-02-20 01:21:13',67.28,61.7],....

maybe a better way to phrase the question is:

If I do :

var jsonData = <?php include 'getData.php' ?> ;

everything works.

If I do :

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

It does not work. However at that point :

 document.write(jsonData); 

outputs the exact same thing as getData.php does.

asgallant

unread,
Feb 20, 2014, 6:35:44 PM2/20/14
to google-visua...@googlegroups.com
The string is not valid JSON, which is the problem.  The strings internal to the JSON have to be double-quoted, eg: ['Time','Temperature', 'Humidity'] should be ["Time","Temperature", "Humidity"]

mkin...@gmail.com

unread,
Feb 20, 2014, 6:47:06 PM2/20/14
to google-visua...@googlegroups.com
Made that change. Still not working. Im sceptical that the quotes are an issue, since it works fine with single quotes from PHP instead or if I cut and paste that array into :

var data = new google.visualization.arrayToDataTable(

 [ ['Time','Temperature', 'Humidity'], ['2014-02-20 01:06:21',68.54,51.9],['2014-02-20 01:09:09',68.18,59.9],['2014-02-20 01:12:16',67.64,68.6],['2014-02-20 01:15:14',67.64,73.9],['2014-02-20 01:19:06',67.82,66.1],['2014-02-20 01:21:13',67.28,61.7],....

)

Works just fine. 

asgallant

unread,
Feb 20, 2014, 7:05:44 PM2/20/14
to google-visua...@googlegroups.com
The quotes are requirement for JSON, but not for standard javascript notation.  Run this in Chrome and see if there are any error messages in the developer's console.

mkin...@gmail.com

unread,
Feb 20, 2014, 9:07:45 PM2/20/14
to google-visua...@googlegroups.com
I seem to have gotten you off on the wrong track. There is nothing wrong with the array. When I say it works, I mean the chart draws correctly when I plug in that array either manually, or by assigning it to a variable, or by having a php script write it out. It only does not work if I use the jquery ajax call. However, while it does not work that way, the actual contents of the jsonData variable are character by character identical from the earlier methods. 

asgallant

unread,
Feb 21, 2014, 10:12:24 AM2/21/14
to google-visua...@googlegroups.com
With this code:

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

jsonData is a string, like this:

"[ ['Time','Temperature', 'Humidity'], ['2014-02-20 01:06:21',68.54,51.9],['2014-02-20 01:09:09',68.18,59.9],['2014-02-20 01:12:16',67.64,68.6],['2014-02-20 01:15:14',67.64,73.9],['2014-02-20 01:19:06',67.82,66.1],['2014-02-20 01:21:13',67.28,61.7],...]"

It is equivalent to this:

var jsonData = "<?php include 'getData.php'; ?>";

not this:

var jsonData = <?php include 'getData.php'; ?>;

You don't want a string, you want an array.  In order to get an array from that string, you have to use JSON.parse, but the rules for JSON specify that all internal strings must use double-quotes.  Switch the single-quotes to double-quotes, and use this line to construct your DataTable:

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

You can confirm that it works by performing a string replace on jsonData:

jsonData = jsonData.replace(/'/g, '"');
var data = google.visualization.arrayToDataTable(JSON.parse(jsonData));

mkin...@gmail.com

unread,
Feb 21, 2014, 1:11:40 PM2/21/14
to google-visua...@googlegroups.com
I just ended up reworking the php to output a DataTable instead of an array and then massaged things further to go to an Annotation Chart for the zoom functionality. I had to explode the SQL timestamp into a Date object and your post to someone else about that was very helpful. Next trick is to figure out how to get the users zoom or scroll settings, ie the user's viewpoint, of the Annotation Chart to survive the timed calls to redraw the chart with new datapoints.  

asgallant

unread,
Feb 21, 2014, 1:31:14 PM2/21/14
to google-visua...@googlegroups.com
Call the getVisibleChartRange method of the chart to get the currently selected range.

mkin...@gmail.com

unread,
Feb 23, 2014, 12:14:20 AM2/23/14
to google-visua...@googlegroups.com
Back to this same issue on another chart and it is still not working. 



        var jsonData = $.ajax({
         url: "getData-roombars.php",
         dataType:"json",
         async: false
         }).responseText;

        jsonData = jsonData.replace(/'/g, '"');

var data = new google.visualization.arrayToDataTable(

JSON.parse(jsonData)



//[ ['Sensor', 'Temp', { role : 'style' }], ['Baby',72.5,'green'], ['Main',72.05,'green'], ['A',72.95,'green'], ['C',70.5866,'green'], ['D',56.8616,'blue'],]


        );


jsonData is [ ['Sensor', 'Temp', { role : 'style' }], ['Baby',72.5,'green'], ['Main',72.05,'green'], ['A',72.95,'green'], ['C',70.5866,'green'], ['D',56.8616,'blue'],]
if I comment out the JSON.parse(jsonData) instead of the array, it works. 

I feel like Im going a long way around when instead there should be a way to have the jquery return an array instead of a string, or even simpler to just tell arrayToDataTable to just ignore the leading and trailing quotes. Someone, and maybe its me, is making this way way way way way harder than it needs to be. 

asgallant

unread,
Feb 24, 2014, 11:36:05 AM2/24/14
to google-visua...@googlegroups.com
jQuery will parse the JSON for you, but it has to be valid JSON.  PHP provides a method of creating JSON from arrays, via the json_encode function, which should take care of any quoting issues that are giving you problems.  As an example:

$foo = array(
    'bar' => array('cad', 'qud', 'fiz'),
    'baz' => 7
);

echo json_encode($foo);

outputs a JSON string like this:

'{"bar":["cad","qud","fiz"],"baz":7}'

Here's an example PHP script that fetches data from a database and outputs a JSON representation of a DataTable:

<?php
try {
  $db = new PDO('mysql:dbname=myDatabase', 'myUsername', 'myPassword');
}
catch (PDOException $e) {
  die("{error: {$e->getMessage()}}");
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $db->prepare("SELECT foo, bar, baz FROM myData");
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$data = array (
    'cols' => array( 
        array('label' => 'Foo', 'type' => 'string'), 
        array('label' => 'Bar', 'type' => 'number'), 
        array('label' => 'Baz', 'type' => 'number')
    ),
    'rows' => array()
);

foreach ($results as $r) {
    $data['rows'][] = array('c' => array(
        array('v' => $r['foo']), 
        array('v' => $r['bar']), 
        array('v' => $r['baz'])
    ));
}
echo json_encode($data, JSON_NUMERIC_CHECK);
?>

You can use it like this:

$.ajax({
    url: "getData-roombars.php",
    dataType: "json",
    success: function (jsonData) {
        var data = new google.visualization.DataTable(jsonData);
        // draw chart(s) with data
    }
});

mkin...@gmail.com

unread,
Feb 25, 2014, 12:24:30 AM2/25/14
to google-visua...@googlegroups.com
While more cumbersome than just dealing with the basic data in an array, Ive beeen outputting a DataTable for multiple charts and gotten it working fine. I have still not gotten an array through arrayToDataTable even once however.

Ive used single quotes, double quotes, json_encode, JSON.parse, and many other things in every possible combination, but nothing formats things the way that arrayToDataTable wants if I use jquery at all.

The array looks like :

[["Sensor", "Temp", { role : 'style' }], ["Baby",71.15,"green"], ["Main",71.2616,"green"], ["A",75.425,"green"], ["C",69.575,"blue"], ["D",60.6866,"blue"],]

This is for a column chart, and I cannot find a way get the third data column to work with a DataTable call, I suspect due to none of the listed "types" working for that column.  If I plug in the array directly into arrayToDataTable it works like a charm. But now I'm back to banging my head against some way to force arrayToDataTable to take input from jquery. 

So Im back to... 

this works:

var data = new google.visualization.arrayToDataTable(  [["Sensor", "Temp", { role : 'style' }], ["Baby",71.15,"green"], ["Main",71.2616,"green"], ["A",75.425,"green"], ["C",69.575,"blue"], ["D",60.6866,"blue"],] );
 
this works :

var data = new google.visualization.arrayToDataTable ( <?php include 'getData-roombars2.php'?>); 

(also looks identical to above when viewed as html source in browser)


This does not work:

var jsonData = $.ajax({
         url: "getData-roombars2.php",
         dataType:"json",
        async: false
         }).responseText;



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


If I do a json_encode on the php side, I get :

" [[\"Sensor\", \"Temp\", { role : 'style' }], [\"Baby\",74.1866,\"green\"], [\"Main\",74.075,\"green\"], [\"A\",75.7616,\"green\"], [\"C\",72.5,\"green\"], [\"D\",60.0116,\"blue\"],]"

but then neither  var data = new google.visualization.arrayToDataTable( jsonData ); nor  var data = new google.visualization.arrayToDataTable( JSON.parse(jsonData) ); work.
If I use JSON.parse on the javascript side, it just makes an array of each of the characters in the string instead of an array of the elements since it cant seem to figure out which commas to use.
Ive also tried double quotes on the role: "style", but that makes no difference. 

So, my question boils down to .... if my getData-roombars2.php script is going to output something like :
[["Sensor", "Temp", { role : 'style' }], ["Baby",71.15,"green"], ["Main",71.2616,"green"], ["A",75.425,"green"], ["C",69.575,"blue"], ["D",60.6866,"blue"],]

What does the
  
 var jsonData = $.ajax({
         url: "getData-roombars2.php",
         dataType:"json",
         });.responseText;

need to make jsonData the right format for arrayToDataTable?

Ive tried your

 $.ajax({
         url: "getData-roombars2.php",
         dataType:"json",
         success : function (jsonData) {
                var data = new google.visualization.DataTable(jsonData);
                // draw chart(s) with data
                }

         });

Which works fine if I can get the PHP script to output all the extra non functional meta data correctly for a DataTable, But since I cant find documentation on how to do the 'type' for the third data column in a column chart, Im forced back to outputting an array. I'd like to be able to use array's since they are a much simpler anyhow, which would seem to be the point of arrayToDataTable. 

asgallant

unread,
Feb 25, 2014, 10:57:01 AM2/25/14
to google-visua...@googlegroups.com
This:

{ role : 'style' }

is a problem.  It should be this:

{ "role" : "style" }

Also, the railing comma at the end of the array is a problem for IE:

[["Sensor", "Temp", { role : 'style' }], ["Baby",71.15,"green"], ["Main",71.2616,"green"], ["A",75.425,"green"], ["C",69.575,"blue"], ["D",60.6866,"blue"],] <-- this comma

If you build your data as an array in PHP and use json_encode, it will take care of all of the nitty-gritty stuff for you, so you don't have to deal with it.  As an example, this PHP would output your array in the correct format:

$myArray = array(
    array('Sensor', 'Temp', array('role' => 'style')),
    array('Baby', 71.15, 'green'),
    array('Main', 71.2616, 'green'),
    array('A', 75.425, 'green'),
    array('C', 69.575, 'blue'),
    array('D', 60.6866, 'blue')
);
echo json_encode($myArray);

If you need more help with this, perhaps you could post your PHP code and I could help you get it to output the correct format?

mkin...@gmail.com

unread,
Feb 25, 2014, 2:35:53 PM2/25/14
to google-visua...@googlegroups.com
I think we are on the right track now, however....

Your code : 

$myArray = array(
    array('Sensor', 'Temp', array('role' => 'style')),
    array('Baby', 71.15, 'green'),
    array('Main', 71.2616, 'green'),
    array('A', 75.425, 'green'),
    array('C', 69.575, 'blue'),
    array('D', 60.6866, 'blue')
);
echo json_encode($myArray);

my code:

$array[0] = array("Sensor", "Temp", array('role' => 'style'));
foreach ($sensors as $sensor) {

... some calculations and sql

$array[] = array($sensorname[$sensor],$dialdata[$sensor],$color);

}

echo json_encode($array);


They essentially the same, cept how mine gets the values to put into the array. Output from both is exactly the same. Neither actually work however.

Output is : 

[["Sensor","Temp",{"role":"style"}],["Baby",71.15,"green"],["Main",71.2616,"green"],["A",75.425,"green"],["C",69.575,"blue"],["D",60.6866,"blue"]]

If I plug that directly in with :

var data = new google.visualization.arrayToDataTable( [["Sensor","Temp",{"role":"style"}],["Baby",71.15,"green"],["Main",71.2616,"green"],["A",75.425,"green"],["C",69.575,"blue"],["D",60.6866,"blue"]] );

It does not work:

However, if I manually change the quotes around the colors to single quotes, it does work. 


Of course, 
var jsonData = $.ajax({
         url: "getData-roombars2.php",
         dataType:"json",
               }) ;

JSON.parse(jsonData);

is still spitting out an array of single characters, with your php or mine, but thats irrelevant till the array Im actually trying to pass to arrayToDataTable has all the quotes and double quotes exactly the way it wants.

asgallant

unread,
Feb 25, 2014, 3:54:58 PM2/25/14
to google-visua...@googlegroups.com
This doesn't work?

$.ajax({
    url: "getData-roombars.php",
    dataType: "json",
    success: function (jsonData) {
        var data = google.visualization.arrayToDataTable(jsonData);
        // draw chart(s) with data
    }
});

Note there is no "new" keyword in front of the arrayToDataTable call.
Reply all
Reply to author
Forward
0 new messages