PHP variable in JS within the While

1

I am creating a chart using Chart.js and PHP, I would like the value to come from an array in PHP with the index of a JS variable. This is the code 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>
    
asked by anonymous 14.01.2016 / 14:34

1 answer

3

PHP runs first, and only when it finishes does JS run. PHP runs on the server, and JS on the client (browser). I suggest you mount the data structure in PHP, and make it ready for JS. Something like this (assuming $ind is declared and has a numeric 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>
    
14.01.2016 / 14:55