I've successfully managed to create a line chart by retrieving the dataset from an ajax call when the line chart only has a single line. I now need to create a line chart with 2 lines, but I can't get it working.
My ajax return data is built in php. This is the code:
$returnData['line'] = array(
'type' => 'line',
'title' => 'Title',
'labels' => array('Jan','Feb'),
'datasets' => array(
array(
'data' => array(0,50),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
),
array(
'data' => array(10,20),
'borderColor' => "#8e5ea2",
'label' => "Label 2",
'fill' => true
)
)
);
echo json_encode($returnData);
My jQuery ajax call is:
$.ajax({
url: "https://example.com/chart_data",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
console.log(data.datasets);
var ctx = document.getElementById("linechart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: [data.datasets],
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
The data looks good when I view what has been logged in the console, so I don't know why this isn't working. All I get is the chart, but no lines.
I'm looking for a future-proofed solution where I can add as many lines as needed to the chart just by amending the php code, without then having to change the jQuery too.