'How Refresh chart js data with same variable name
I am facing an issue while refreshing the data using the same variable. Every time data get changed in a variable(mydata) but after an update the chart loaded with same data.while click the refresh button chart get reloded but always showing the old chart in chart
<button type="button" onclick="refresh()">Refresh</button>
<canvas id="mychart"></canvas>
<script >
var config = {
type: 'bar',
options: {
scales: {
y: {
beginAtZero: true
}
}
},
};
var myChart=null;
function refresh(){
$.ajax({
url: '/mydata',
method: 'POST',
data: {"user":user},
async: false,
success: function(data) {
mydata = data;
}
})
config.data = {
labels: ["jan","Feb","Mar","Apr","may","june","july"],
datasets:
[{
data: mydata,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 205, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(201, 203, 207, 0.2)'
],
borderColor: [
'rgb(255, 99, 132)',
'rgb(255, 159, 64)',
'rgb(255, 205, 86)',
'rgb(75, 192, 192)',
'rgb(54, 162, 235)',
'rgb(153, 102, 255)',
'rgb(201, 203, 207)'
]
}]
};
ctx = document.getElementById('mychart');
if(myChart == null){
myChart = new Chart(ctx, config);
} else{
myChart.data.datasets[0].data=mydata;
myChart.update();
}
}
</script>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|