3

I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function? My PHP code is as follows :

while ($graph_result = mysqli_fetch_row($graph)) 
{
    $graphCount = $graph_result[0];
    $graphMonth = $graph_result[1];
    echo $graphCount; // This works
    echo $graphMonth;
}

This gives me in result of two rows, each contains two values listed below:

enter image description here

Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Months', 'users'],
        [graphMonth, graphCount]  // Here I have to place PHP values !
    ]); 
}

So how to pass this values to JS ???

3 Answers 3

1

Try the below code,

In PHP

$i = 0;
while ($graph_result = mysqli_fetch_row($graph)) 
{
    $graph_values[$i]["count"] = $graph_result[0];
    $graph_values[$i]["month"] = $graph_result[1];
    $i++;
}

In script,

<script>
    <?php foreach($graph_values as $key){ ?>
    drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
    <?php } ?>

function drawChart(graphCount, graphMonth) {
    var data = google.visualization.arrayToDataTable([
        ['Months', 'users'],
        [graphMonth, graphCount] 
    ]); 
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

1
<?php while ($graph_result = mysqli_fetch_row($graph)) 
{
   ?>
<script>
function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Months', 'users'],
        [<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
    ]); 
}
</script>
<?php
}
?>

I don't know if it is best practice or not..

Comments

0

You can use json to do that.
In your while loop, build an associative array and encode it in json:

$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph)) 
{
    $graphCount = $graph_result[0];
    $graphMonth = $graph_result[1];
    $jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';

And then recover it in your javascript:

var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
    var data = google.visualization.DataTable();
    data.addColumn('number','Months');
    data.addColumn('number','users');
    data.addRows(json_data);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.