Reputation:
Hey there actually I am retrieving some data from database The data is is like this format
id: "5"
p_amount: "120"
p_date: "09/20/2019"
p_id: "12345"
p_method: "Bank"
p_status: "OPEN"
This is what i did in ajax response, I convert the month of date in its name
success: function(response){
var obj=JSON.parse(response);
if(obj!=""){
$.each(obj, function(i, item) {
var selectedMonthName = months[obj[i].p_date.slice(0,2)-1];
});
}
Now i have another file of name main.js and i made a chart in javascript
(function ($) {
// USE STRICT
"use strict";
try {
//WidgetChart 1
var ctx = document.getElementById("widgetChart1");
if (ctx) {
ctx.height = 115;
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July','August','September','October','November','December'],
type: 'line',
datasets: [{
data: [0, 0, 0, 0, 0, 0, 0,0,0,0,0,0], //Here data should be added e.g, if month is september the value p_amount should add here in 8th index
label: 'Dataset',
backgroundColor: 'rgba(255,255,255,.1)',
borderColor: 'rgba(255,255,255,.55)',
},]
},
options: {
maintainAspectRatio: true,
legend: {
display: false
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
responsive: true,
scales: {
xAxes: [{
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent'
}
}],
yAxes: [{
display: false,
ticks: {
display: false,
}
}]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 0
},
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4
}
}
}
});
}
} catch (error) {
console.log(error);
}
})(jQuery);
Now i want when i get the month name the data(which is retrieved from DB) in other js file should be updated
Upvotes: 0
Views: 115
Reputation: 2249
We used something like this, made chart.js object global, set its data from Ajax response and called update method.
var labels = [];
var data = [];
var smallDB = {};
var lastYear = 0;
var limit = 5; // limit history to (5) years
var obj = TestData();
for (var i in obj) {
var d = new Date(obj[i].b_date);
var idy = d.getFullYear();
lastYear = Math.max(lastYear, idy)
var num = parseInt(obj[i].b_amount);
smallDB[idy] = (smallDB[idy] || 0) + num;
}
lastYear++;
for(var i=0;i<limit;i++) {
labels[i] = i+lastYear-limit;
data[i] = smallDB[i+lastYear-limit] || 0;
console.log(labels[i], data[i]);
}
function TestData() {
return [{
b_date:"11/01/2017",
b_amount:"110"
},{
b_date:"10/01/2016",
b_amount:"100"
},{
b_date:"01/01/2020",
b_amount:"200"
},{
b_date:"12/01/2018",
b_amount:"120"
}];
};
This one limits last 5 years.
Upvotes: 1