PHP variable in JS inside While

Asked

Viewed 262 times

1

I am creating a chart using Chart.js and PHP, I would like the value to come from a PHP array with the input of a JS variable. This is the code of what I tried to do.

 <script type="text/javascript">
var ctx = document.getElementById("piechart").getContext("2d");
var data = [];
var i = 0;

while(i <= <?print $ind;?>)
{
data.push({
    <?$variavelphp = "<script>document.write(i)</script>";?>
    value: <?print $array[$variavelphp];?>,
    color:"#F7464A",
    highlight: "#FF5A5E",
    label: "Red"
});
i++;
}
}

var options = {
animateScale: false
};

var myNewChart = new Chart(ctx).Pie(data,options);

</script>
  • what problem are you encountering? be clearer with your doubt please.

1 answer

3


PHP runs first, and only when it finishes will JS run. PHP runs on the server, and JS runs on the client (browser). I suggest you build the data structure in PHP, and pass it ready to JS. Something like that (assuming $ind is declared and has a numerical value):

<script type="text/javascript">
var ctx = document.getElementById("piechart").getContext("2d");
var data = [];
var i = 0;

<?php
$dados = array();
while($i <= $ind)
{
    $dados[] = array(
        "value" => $array($i), 
        "color" => "#F7464A",
        "highlight" => "#FF5A5E",
        "label" => "Red"
    );

    $i++;
}
?>

var options = {
    animateScale: false
};

var myNewChart = new Chart(ctx).Pie(<?php echo json_encode($dados) ?>, options);

</script>
  • It didn’t work. .

  • It is that in the question it is not clear which dice you want to show. I supus that it were array[$i]. You need to explain better what the die is and where it comes from

Browser other questions tagged

You are not signed in. Login or sign up in order to post.