Trying to put a PHP math result into JavaScript chart

I’ve been trying to figure this out for days. I hope I can explain this clear. I am trying to call up the results of this simple math equation in JavaScript code below:

             <?php  
             $x=37;  
             $y=15;  
             $z=$x-$y;  
             echo " ",$z;  
             ?> 

part of the script code

        { y: $z, label: "slice" },
        { y: 2, label: "pepper" },
        { y: 15, label: "sprite" },
        { y: 23, label: "coke" }

I now trying to put the $z in the script code

i tried using JavaScript and call tags, but that just messes up the JavaScript code. It only works if the number is posted only. Let know if what I did is possbile

>Solution :

To pass the value of $z from PHP to JavaScript, you can include the value of $z in a JavaScript block in your PHP code:

<?php  
$x = 37;  
$y = 15;  
$z = $x - $y;  
echo '<script>var z = ' . $z . ';</script>';  
?> 

<script>
// use the variable z in your JavaScript code
var dataPoints = [
    { y: z, label: "slice" },
    { y: 2, label: "pepper" },
    { y: 15, label: "sprite" },
    { y: 23, label: "coke" }
];
</script>

In this example, the PHP code outputs a JavaScript block that sets the value of a variable called "z" to the value of $z. The JavaScript code then uses the "z" variable in the dataPoints array.

This approach should allow you to use the value of $z in your JavaScript code.

Leave a Reply