views:

519

answers:

1

I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity...

<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>

I would like to access these three arrays in Javascript to update my Google Chart dynamically.

<script type="text/javascript">

google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);

var linevol = new Array;  // This would be the first array passed from PHP
var loanvol = new Array;  // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP

function drawChart() {
    var data = new google.visualization.DataTable();

    data.addColumn('string', 'Cluster');
    data.addColumn('number', 'Loans');
    data.addColumn('number', 'Lines');

/* create for loops to add as many columns as necessary */

var len = jsonarray.length;

    data.addRows(len);

for(i=0; i<len; i++) {

data.setValue(i, 0, ' '+clusters[i]+'');     /* x-axis */
data.setValue(i, 1, linevol[i]);   /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]);   /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>
+5  A: 

You probably want them to become Javascript variables. When your php executes, it creates code your web browser then interprets. So you want to define javascript strings using php. For example:

<script type="text/javascript">
    var encoded_line_volume = <?php echo json_encode($LineVol) ?>;
    var encoded_loan_volume = <?php echo json_encode($LoanVol) ?>;
    var encoded_cluster_name = <?php echo json_encode($ClusterLine) ?>;
</script>

Then those variables are accessible to subsequent javascript.

Ken
thanks, ken... will I need to parse each variable to create corresponding javascript arrays?
brussels0828
Parse in Javascript? No, not if the array is a normal array in PHP. Json encodes the variable so that it interprets directly as a javascript variable -- that's why there are no quotes around them.If you view the page source, you'll see what I mean.
Ken
you're the man, Ken... Thanks, bro.
brussels0828
No problem. :) Glad I could help.
Ken