0

I'm trying to build a chart using Chart.js library.

I don't know where is the issue but my HTML gives me a blank page, can you help me ?

This is the API that extract data from my db (MYSQL). The API works.

<?php

[...]

$sql = "SELECT COUNT(Diagnosi_Principale) AS conteggio, Descrizione,     Diagnosi_Principale
FROM DIAGNOSI JOIN CODICI_DIAGNOSI ON     Diagnosi_Principale=CODICI_DIAGNOSI.Codice_Diagnosi
GROUP BY Diagnosi_Principale
ORDER BY conteggio, CODICI_DIAGNOSI.Codice_Diagnosi, Descrizione;";

$result = $conn->query($sql);

$jsonArray = array(); 


if ($result->num_rows > 0) {
//Converto i risultati in un array associativo
  while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['conteggio'] = $row['conteggio'];
$jsonArrayItem['Descrizione'] = $row['Descrizione'];

array_push($jsonArray, $jsonArrayItem);
}

echo json_encode($jsonArray);
}

[...]

?>

After this I should load my JSON data to show them in chart.js and seems that something is wrong here.

<script>
    $(window).load(function () {
    var ctx = document.getElementById('canvas');
    $.ajax({  
                type: 'GET',
                dataType: 'json',
                url: '/api/getOccorrenzaTumori.php',
                success: function(response){
                     if(response){
                            var labels = [];
                            var data = [];

                            $.each(response, function(index, value){
                               labels.push(value.Descrizione); 
                               data.push(value.conteggio); 
                            });
                            var chart = new Chart(ctx, {
                               type: 'bar',
                               data: {
                                labels: labels,
                                datasets: [{
                                   data: data
                                }]
                            }
                            });
                      }
                },
                error: function(xhr, ajaxOptions, thrownError){
                       alert(thrownError);
                },
             });
   });
</script>

Thanks in advance

  • why don't you check the console? And also try validating your JSON, there might be a case it is invalid. http://jsonlint.com/ – anshulix May 29 '16 at 08:22
  • This might be a [multiple-chartjs-in-the-same-page](http://stackoverflow.com/questions/24555823/multiple-chartjs-in-the-same-page) problem – nilsK May 29 '16 at 08:38
  • Console gives me this error : Chart.js:30 Uncaught TypeError: Cannot read property 'offsetWidth' of undefined – Luigi Russo May 29 '16 at 08:48
  • can you also add your json string that si returned – mohsin139 May 29 '16 at 12:33

0 Answers0