I'm trying to pass chart values from a java servlet to a web page. The chart should display dates as x and integers as y.
The servlet sends an array of objects that contain year, month, day, and value.
The function:
function getMultiChart() {
jQuery.ajax({
type: "POST",
data: {formType: 'getProjection'},
url: "ChartServlet",
dataType: 'json',
asynch: false,
success: function (data) {
var obj = JSON.stringify(data);
var obj2 = JSON.parse(obj);
var tmpArr = new Array();
jQuery.each(obj2, function (prop, val){
tmpArr.push("x: new Date(" + Number(val.year) + "," + Number(val.month) + "," + Number(val.day) + "), y: " + Number(val.value));
});
var chart = new CanvasJS.Chart("chartContainer",{
title: {
text: "Manpower"
},
data: [
{
type: "column",
indexLabel: "{y}",
indexLabelPlacement: "outside",
indexLabelOrientation: "horizontal",
showInLegend: true,
name: "Overtime Personnel",
dataPoints: tmpArr
}
]
});
chart.render();
},
error: function () {
console.log(data);
}
});
}
When I run it, I get the abovementioned error in ChartJS.js.
It works fine if I replace the json data with hard-coded values like:
var tmpArr = [
{x: new Date(2020, 01, 1), y: 18},
{x: new Date(2020, 01, 2), y: 0},
{x: new Date(2020, 01, 3), y: 0},
{x: new Date(2020, 01, 4), y: 0},
{x: new Date(2020, 01, 5), y: 0},
{x: new Date(2020, 01, 6), y: 0},
{x: new Date(2020, 01, 7), y: 0},
{x: new Date(2020, 01, 8), y: 0},
{x: new Date(2020, 01, 9), y: 0},
{x: new Date(2020, 01, 10), y: 0},
{x: new Date(2020, 01, 11), y: 0},
{x: new Date(2020, 01, 12), y: 0}
]
Where am I messing up here?
My mistake is that the data array has to be an array of objects, not a string.
Even with this, I still couldn't get the "x: new Date(...)" part to work.
The working code is: