NeverPhased
NeverPhased

Reputation: 1566

How to include PHP in Javascript; Google Chart API

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.

Upvotes: 3

Views: 5274

Answers (4)

NeverPhased
NeverPhased

Reputation: 1566

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

Upvotes: 0

Jordan
Jordan

Reputation: 4628

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/

Upvotes: 2

qw3n
qw3n

Reputation: 6334

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>

Upvotes: -1

aefxx
aefxx

Reputation: 25279

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); ?>);

Upvotes: 2

Related Questions