3

I am working with the google chart visualization API.

I have a variable in php:

`$value` 

which contains the following: ['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]

I want to use this $value below in data.addRows as follows however the output I am getting is blank

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Period');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');
    data.addRows([ 

   <?php echo $value ?>

            ]);

    var options = {
      width: 400, height: 240,
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script> 

After some research it seems it is Ajax I am trying to attempt. Is this correct? Is there a simple way I can return the value $value to data.addRow??

Here is the process to which $value is set:

$i = "0";   
$period = "0";
$chartrow = array();
$unitpriceNumR = 3

while ($i<3)

{


$chartrow[$i] = "['".$period."',".$sPrice[$i].", ".$uPrice[$i]."]";


$period++;
$i++;

}

switch ($currentStage)
{

case "0":

$value = $chartrow[0];
    break;



case "1":

$value = $chartrow[0];  
    break;



case "2":

$value = $chartrow[0].",".$chartrow[1];
    break;


}

In this example if $currentStage = "2" then $value is set to ['0',0, 0],['1',65, 35]

Ok now I have even tried a copy and paste of google code into my file and still no success of seeing a graph. (code taken from:http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html)

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Year');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');
    data.addRows([
      ['2004', 1000, 400],
      ['2005', 1170, 460],
      ['2006',  860, 580],
      ['2007', 1030, 540]
    ]);

    var options = {
      width: 400, height: 240,
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
 </script>

Using this code

$chartrow = array();


for ($i = 0; $i < 3; $i++ )
{
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
echo $chartrow;

}

results in $chartrow displaying the word "Array" to the screen.

NeverPhased
  • 1,546
  • 3
  • 17
  • 31
  • possible duplicate of [Pass a PHP string to a Javascript variable (including escaping newlines)](http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines) – John Carter Dec 09 '11 at 23:32
  • Think I may have found what is wrong. Here is the code I am using: http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html However when I hit Visualization Playground (link above the code), the code is structured different. http://code.google.com/apis/ajax/playground/?type=visualization#line_chart – NeverPhased Dec 09 '11 at 23:54

4 Answers4

2

Please have a look at the JSON encode function provided with PHP. This will let you echo or print out a JSON encoded string that JavaScript transforms into a native object.

$value = array(
    array('0', 0, 0),
    array('1', 65, 35),
    array('2', 88, 35),
    ...
);

...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);

EDIT

$i = 0; 
$chartrow = array();
$unitpriceNumR = 3

for (; $i < 3; $i++ )
    $chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);

switch ($currentStage) {
    case "0":
    case "1":
        $value = $chartrow[0]; 
        break;

    case "2":
        $value = array_slice($chartrow, 0, 2);

    default:
        // You should have some default value, seriously!!!
}

// Then go the json_encode way, it's safer and easier to maintain!
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');

// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
aefxx
  • 24,835
  • 6
  • 45
  • 55
2

Change [<?php echo $value ?>] to <?php echo json_encode($value) ?>

echo $value produces Array(5) because PHP doesn't natively know how to represent an array as a string.

echo json_encode($value) produces:

[['0',0, 0],['1',65,35],['2',66,35],['4',35,35],['5',99, 100]]

so you don't need brackets around the <?php ... ?>.

http://php.net/manual/en/function.json-encode.php

EDIT: thanks for clarifying how the PHP variables are formed.

The problem is that you're manually converting arrays into strings, when you should let $json_encode do all of the work for you.

Revised version of the PHP code:

$chartrow = array();
$unitpriceNumR = 3;

for ($i=0; $i<=2; $i++)
    $chart_row[$i] = array($i, $sPrice[$i], $uPrice[$i];

switch ($currentStage)
{
    case '0':
    case '1':
        $value = $chartrow[0];
        break;

    case '2':
        $value = array($chartrow[0], $chartrow[1]);
        break;
}

EDIT2: I tried what you did (replacing the php block with what we expect the php block to produce) and it didn't work for me either. Firebug says 'Container is not defined' in Google's own code.

You forgot to add a div to your document. Add <div id='chart_div'></div> after the script.

So we're on the same page: http://jsfiddle.net/daemon/nnpeE/

Jordan
  • 4,510
  • 7
  • 34
  • 42
  • ok I've done that and nothing is being outputted (no chart displayed). I am following this code http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html – NeverPhased Dec 09 '11 at 23:29
  • ok so this is what I have data.addRows(); but still no graph showing. The file is a php file. I have closed the php tags for the js... – NeverPhased Dec 09 '11 at 23:33
  • What do you see when you view the source of the page? Does it show `data.addRows([['0',0, 0],['1',65,35],['2',88,35],['3',66,35],['4',35,35],['5',99,100]]);`? – Jordan Dec 09 '11 at 23:35
  • it shows data.addRows("['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]"); – NeverPhased Dec 09 '11 at 23:37
  • I suppose the problem is how I set $value – NeverPhased Dec 09 '11 at 23:37
  • Try changing `echo json_encode($value)` to `echo json_encode($chartrow)`. – Jordan Dec 09 '11 at 23:41
  • ill try now, please see above, I fully show how $value comes about. – NeverPhased Dec 09 '11 at 23:46
  • Doesn't work...I even tried data.addRows([['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]]); and its not working...hmmm – NeverPhased Dec 09 '11 at 23:50
  • See my edits. The script will work when you add the `div`. The php will (hopefully) work if you leave all the array-to-string conversion to `json_encode`. – Jordan Dec 10 '11 at 00:05
  • data.addRows([ null ]); from view source When I use data.addRows([]); The graph is showing but no data. – NeverPhased Dec 10 '11 at 00:21
  • Again, the problem is setting $value. After using your code (I took away the underscore in $chart_row, and added a bracket in the same line to fix it up) when I echo $chartrow it outputs the word "array" – NeverPhased Dec 10 '11 at 00:39
0

Here is the answer to this problem PHP: How to pass multiple variables to an array?

Community
  • 1
  • 1
NeverPhased
  • 1,546
  • 3
  • 17
  • 31
-1

Whenever I have values like that I do this as my first script on the page and it seems to work for me. It also allows me to inspect what is going on with the PHP instead of the variable being hidden in some function. Note that this will create a global variable which might be not what you want.

<script>
var a = [<?php echo($var1) ?>];
</script>

EDIT:
I got your PHP code to work for me. The changes I made was I converted $i to just 0 not "0" The same goes for the switch statement . Also line 4 needs a semicolon after it. Then I put this

<script>
var a = [<?php echo($value) ?>];
</script>

And the output in the page was

<script>
var a = [['0',, ],['1',, ]];
</script>
qw3n
  • 6,236
  • 6
  • 33
  • 62
  • @afexx Well what I was thinking is then in the function he can put `data.addRows(a);` assuming '$var1` = `[...]`. Obviously global variables are not optimal, but the OP can easily see what was outputted by PHP. – qw3n Dec 09 '11 at 23:38