Take json data from php with javascript

Asked

Viewed 51 times

-1

Hello, I’m trying to set up a dynamic chart with Charts.js, the data is in my database, returned this data in a decoded variable in json, which returns me the following:

[{"id_requisicao":"1","0":"1"},{"id_requisicao":"3","0":"3"},{"id_requisicao":"8","0":"8"},{"id_requisicao":"11","0":"11"},{"id_requisicao":"4","0":"4"},{"id_requisicao":"9","0":"9"}]

I have in my Dash.php file javascript with Charts but I can’t get this data, someone can help me?

  var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: <?php echo $exibiDash ?>,
            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)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
  • <?php $exibiDash ?> that means nothing, you need to apply a echo or simply <?=

  • I had forgotten to put the echo but even so did not work, appears only the blank screen, no information or anything

2 answers

0


I was able to find out, the version of my Charts.js was outdated and did not work. and I had to put in options the name of my x and y keys.

 parsing: {
                    xAxisKey: 'nome',
                    yAxisKey: 'valor'
                }

0

Hello, you can convert this data with json_encode() on the php side, move to a javascript object with JSON.parse()

<?php
$json = json_encode($seu_array);
?>
<script>
   datasets: [{
      data: JSON.parse('<?= $json ?>')
   }]

I hope I helped =D

  • Didn’t work, page appears blank

  • tries to create a variable in the global scope of the page as I said, and retrieve it on the console to see what the content is, because it should work, so maybe the error is elsewhere. If she’s not on the console undefined, eh problem in Chart, if Undefined the problem is in php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.