0

Hi I have this array variable in my php file

$data_chart=[95,65,25,12,458,896,325];

and i had create a script as following

 <script>
     var data = <?php echo json_encode($data_chart); ?>;

    </script>

how i can pass the data variable into my chart-data.js file?(without embedding the variable in html tag)

1 Answer 1

1

Well since you are using php like this, the relevant javascript will have to be on the same html document as the canvas element. This following was adapted from the chart.js documentation here. Something like this could work:

<canvas id="myChart" width="400" height="400"></canvas>
<script>
  
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'type',
    data: {
        labels: ["1", "2", "3", "4", "5", "6", "7"],
        datasets: [{
            label: 'my data',
            data: <?php echo json_encode($data_chart); ?>,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderWidth: 1
        }]
    }
});
</script>

If you really cannot have the javascript embedded into the html file, then you could store the php data in local storage through the html file, then read in the javascript file, but that seems unnecessarily difficult.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.