ChartJS with PHP

1

Oops, I'm using ChartJS for graphing, I'm integrating with PHP to send json to the chart

php

$arrLabels = array("January","February","March");
$arrDatasets = array('label' => "My First dataset",'fillColor' => "rgba(220,220,220,0.2)", 'strokeColor' => "rgba(220,220,220,1)", 'pointColor' => "rgba(220,220,220,1)", 'pointStrokeColor' => "#fff", 'pointHighlightFill' => "#fff", 'pointHighlightStroke' => "rgba(220,220,220,1)", 'data' => array('28', '48', '40'));

$arrReturn = array(array('labels' => $arrLabels, 'datasets' => $arrDatasets));

print (json_encode($arrReturn));

js

var ctx = document.getElementById("salesChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        data_retorno
    }
}); 

Value of data_retorno

[  
   {  
      "labels":[  
         "January",
         "February",
         "March"
      ],
      "datasets":{  
         "label":"My First dataset",
         "fillColor":"rgba(220,220,220,0.2)",
         "strokeColor":"rgba(220,220,220,1)",
         "pointColor":"rgba(220,220,220,1)",
         "pointStrokeColor":"#fff",
         "pointHighlightFill":"#fff",
         "pointHighlightStroke":"rgba(220,220,220,1)",
         "data":[  
            "28",
            "48",
            "40"
         ]
      }
   }
]

Where data_retorno is the return of ajax.

The graph that is already loaded with other data, upon receiving this result, simply the lines disappear and nothing happens

    
asked by anonymous 31.05.2017 / 14:10

1 answer

0

The format of the return data has two details that need to be matched to charjs , which are:

  • property data expects an object instead of an array
  • property datasets expects an array instead of an object

Assuming your return is this, we can tailor data_retorno as follows:

var data_retorno = [...] // ... indica todo o conteúdo
data_retorno = data_retorno[0]; // pega o objeto dentro do array
data_retorno.datasets = [].concat(data_retorno.datasets); // cria um array como valor

JSFiddle: link

    
31.05.2017 / 14:47