Chartjs with PHP

Asked

Viewed 1,182 times

1

Oops, I’m using the Chartjs for graphic generation, I am 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 the ajax.

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

  • Maybe the data_retorno is not in the format chartjs expects. You can share with us the value of data_retorno?

  • Opa @Lucascosta edited the question adding the value of data_retorno, vlw

  • try data: data_retorno[0] @sNniffer

  • @Lucascosta gave Chart.js error, error:TypeError: can't assign to properties of (new String(" ")): not an object

1 answer

0

The format of the return data has two details that need to fit the charjs, who are:

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

Assuming your return is this, we can tailor the data_retorno thus:

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: https://jsfiddle.net/wwrtynec/2/

  • I just converted the dataset to @sNniffer array, you can check if it is already an array, if not using the conversion [].concat..

Browser other questions tagged

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