Chart.js data array using PHP, MySQL. How to define datasource from JSON array?

12,449

You could use $js_cols = json_encode($COUNTS,JSON_NUMERIC_CHECK);

and then

data : <?php echo print_r($js_cols,true); ?>
Share:
12,449
Nariman
Author by

Nariman

Updated on June 08, 2022

Comments

  • Nariman
    Nariman almost 2 years

    This is my first question. Kindly apologize for any errors.

    I am trying to draw a chart using chart.js with PHP and MySQL data. The graph I intend to draw is a simple vertical barchart, birth_year vs number of people born. When I display the arrays $BIRTH_YEAR and $COUNTS, I could see the values. I was able to get to the point till json_encode($data_array). When I try to use this encoded array on javascript, I do not get any output, a blank page! Here is my code.

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $data[] = array(
        $row['BIRTH_YEAR']=>$row['counts'],
    );
    $BIRTH_YEAR[]=$row['BIRTH_YEAR'];
    $COUNTS[]=$row['counts'];
    }
    
    // JSON arrays for labels and counts
    $js_labels = json_encode($BIRTH_YEAR,true);
    $js_cols = json_encode($COUNTS,true);
    
    
    var barChartData = {
            labels : '<?php echo $js_labels; ?>',
                        datasets : [
                {
                    fillColor : "rgba(220,220,220,0.5)",
                    strokeColor : "rgba(220,220,220,1)",
                    data : '<?php echo $js_cols; ?>'
                }
    
            ]
                       }
    
    var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
    

    I have included all other required HTML elements in my page. When I use the chart.js sample file I was able to see charts. The only issue is I am not sure how to include arrays in javascript data: part. Thanks in advance.