简体   繁体   中英

Php variables inside Javascript

I am creating a doughnut chart and where I am having trouble is all of my data is being pulled server side. Here is the html for the chart with set values. How would I go about echoing my php variables as the values?

<html>
<head>
<script src="Chart.js"></script>
<style>
body{
padding: 0;
margin: 0;
}
#canvas-holder{
width:25%;
}
</style>
</head>
<body>
<div id="canvas-holder">
<canvas id="chart-area" width="500" height="500"></canvas>
</div>
<script>
var doughnutData = [
{
value: 500,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
},

{
value: 500,
color: "#575757",
highlight: "#777777",
label: "Pre-Production"
},

{
value: 500,
color: "#aaaaaa",
highlight: "#cccccc",
label: "In Production"
}
];
window.onload = function(){
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
};
</script>
</body>
</html>

My php code grabs the data that is need via api and then stores each value in a variable eg.

<?php
$needs_agreement = 148000;
$pre_produciton = 137000;
$in_production = 3678000;
?>

Again, what is the best method for echoing the php variables where value: is above?

UPDATE:

var doughnutData = [
{
value: <?php echo $needs_agreement ?>,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
},

{
value: <?php echo $pre_production ?>,
color: "#575757",
highlight: "#777777",
label: "Pre-Production"
},

{
value: <?php echo $in_production ?>,
color: "#aaaaaa",
highlight: "#cccccc",
label: "In Production"
}
];

The Above code which was suggested as the answer did not work.

Nothing stops you from simply echo'ing PHP variables in the middle of the javascript.

<script>
var doughnutData = [
{
value: <?php echo $some_data ?>,
color:"#941616",
highlight: "#FF0000",
label: "Needs Agreement"
}
</script>

All of the PHP is processed before sending the document to the browser, so the javascript will be complete by the time it gets executed by the client.

I finally got it working, at the very end up of my php file:

echo '<script>' . 'var zx =' . $total_need . '</script>';
echo '<script>' . 'var zy =' . $total_pre . '</script>';
echo '<script>' . 'var zz =' . $total_in . '</script>';

The html section would then look like this:

 var doughnutData = [ { value: zx, color:"#941616", highlight: "#FF0000", label: "Needs Agreement" }, { value: zy, color: "#575757", highlight: "#777777", label: "Pre-Production" }, { value: zz, color: "#aaaaaa", highlight: "#cccccc", label: "In Production" } ]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM