0

I have this Javascript which outputs a chart with some values:

<script type="text/javascript">
      //pie
      var ctxP = document.getElementById("pieChart").getContext('2d');
      var myPieChart = new Chart(ctxP, {
        type: 'pie',
        data: {
          labels: ["Red", "Blue"],
          datasets: [{
            data: [10, 90],
            backgroundColor: ["#F7464A", "#46BFBD"],
            hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
          }]
        },
        options: {
          responsive: true
        }
      });
    </script>

I need to customize some values, as the ones in labels or data, coming from some calculations previously made in PHP.

What I tried so far was unsuccessfull, probably because I am missing something. To simplify what I did, here the code:

//PHP code where I define some variables as strings
<?php
$color1 = "Black";
$color2 = "White";
?>
//Then comes again the Javascript code:
<script type="text/javascript">
  //pie
  var ctxP = document.getElementById("pieChart").getContext('2d');
  var myPieChart = new Chart(ctxP, {
    type: 'pie',
    data: {
      labels: [<?php echo $color1, $color2; ?>], //////////Here my modification
      datasets: [{
        data: [10, 90],
        backgroundColor: ["#F7464A", "#46BFBD"],
        hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
      }]
    },
    options: {
      responsive: true
    }
  });
</script>

This does not work, but I do not understand why.

I also tried with:

     <?php
     $colors = array("Black", "White");
     ?>  

passing the $colors variable, but nothing changes.

What kind of mistake am I making?

How can I fix this?

warcode360
  • 47
  • 5

1 Answers1

-1

In a php file it can be done with json_encode

<?php
// your php code
?>

<script>
    var jsObject = <?php
    echo json_encode([
        'my_variable1' => 'value1',
        'my_variable2' => 'value2'
    ]);
    ?>
    
    console.log(jsObject);
</script>
  • It won't work like that. the jsObject will return a non-parsed json string. You should parse it just like: `JSON.parse(jsObject)`. And also you must wrap the with "" – Adnane Ar Aug 24 '20 at 12:18
  • @AdnaneAr It WILL work. Looks like you haven't tried it exactly as it is written. Php's **json_encode** returns a string value indeed, but then it gets injected directly into html WITHOUT any quotes, so what you get is basically `var jsObject = { ...content goes here }` Therefore it shouldn't be parsed. As for your variant with wrapping in quotes, then it should be parsed then, yes – Vladimir Bakulin Aug 25 '20 at 04:04