Dima Ha
Dima Ha

Reputation: 156

Can't pass variable from PHP to JS

I want to load data from my MySQL server with php code and then use it to draw chart with google charts. the problem is that i can't use the data that quered from my mysql in the java-script code.

PHP code:

  $connection = mysql_connect('127.0.0.1','root','123456');
  mysql_select_db('db_statmarket',$connection);
  $result2 = mysql_query('select sum(`How much read from customer`) as Leads, Date from monitor group by Date;',$connection) or die('cannot show tables');

Here in the javascript code where we can see the var data = ... i want that he will be the table that i quered from my database.

HTML & JS code:

<script type="text/javascript">
  google.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }
</script>

The output need to be seen like these: enter image description here

Upvotes: 0

Views: 381

Answers (1)

Vivien Ln
Vivien Ln

Reputation: 171

Something like that:

<?php
    $connection = mysql_connect('127.0.0.1','root','123456');
    mysql_select_db('db_statmarket',$connection);
    $result2 = mysql_query('select sum(`How much read from customer`) as Leads, Date from monitor group by Date;',$connection) or die('cannot show tables');

    $json = array();
    while($row = mysql_fetch_assoc($result2)) {
        $json[] = $row;
    }
?>
<script type="text/javascript">
    var data = <?php echo json_encode($json); ?>;
    // chart code here
</script>

If your javascript is in a .js file, you can:

  1. Make your data variable "global" (though it would be better to wrap it in a global object, in order to not pollute global namespace)
  2. Use Ajax (in this case the php code would be identical, but in a separate file returning only JSON data)

Upvotes: 3

Related Questions