Home > Net >  Display php array data in chart.js javascript
Display php array data in chart.js javascript

Time:10-28

I'm trying to display a chart using chart.js, the chart data would be gotten from a php mysql database and displayed into the function below;

const pieChart2 = new Chart(document.getElementById('chats'), {
  type: 'pie',
  data: {
    labels: ['John Mark', 'Sandra Friday', 'Kelvin Russel'], //php code to display data
    datasets: [{
      data: [25, 12, 4], //php code to display data
      backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
      hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
    }]
  },
  options: {
    responsive: true
  }
});

I am able to fetch data from my database

$rscht = mysqli_query($conn,"SELECT users.name, COUNT(*) AS times FROM chat_logs INNER JOIN users ON chat_logs.sender_email = users.email GROUP BY chat_logs.sender_email ORDER BY times DESC");

I am also able to convert the data to a php array using jsonencode

<?php 
    $chatstack = array(); 
    while($userchat= mysqli_fetch_array($rscht)){
   
    $chatstackitem['label'] = $userchat['name'];
    $chatstackitem['value'] = $userchat['times'];
    array_push( $chatstack, $chatstackitem );
    }
    $chatArray = json_encode( $chatstack );
    print_r( $chatArray );

    ?>

The result above gives me

  <canvas id="chats"></canvas>
[{"label":"John Mark","value":"25"},{"label":"Sandra Friday","value":"12"},{"label":"Kelvin Russel","value":"4"}]

My question now is, how can I display the php code that shows all the array of names (label) in the labels: section

labels: ['John Mark', 'Sandra Friday', 'Kelvin Russel'], //php code to display data

and also display the php code that shows values in data section

 data: [25, 12, 4], //php code to display data

CodePudding user response:

So PHP is a backend server side technology, JS in this context is a client side only context. PHP will allow you to print this json encoded data into a script block that will allow you to assign this data to a JS variable.

Alternatively you could use a cookie to store this data and read it from there.

CodePudding user response:

You need to supply the labels and data separately. You could create two variables in your loop for this:

$chatLabels = []; 
$chatData = [];
while ($userchat= mysqli_fetch_array($rscht)) {
      $chatLabels[] = $userchat['name'];
      $chatData[] = $userchat['times'];
}
$chatLabelsJson = json_encode($chatLabels); // ["John Mark","Sandra Friday","Kelvin Russel"]
$chatDataJson = json_encode($chatData); //["25","12","4"]

Alternatively you could use array_column to pull out the data from your existing $chatstack array:

$chatLabels = array_column($chatstack, 'label');
$chatData = array_column($chatstack, 'value');
$chatLabelsJson = json_encode($chatLabels); // ["John Mark","Sandra Friday","Kelvin Russel"]
$chatDataJson = json_encode($chatData); //["25","12","4"]
  • Related