0👍
Try calling your ajax method after initializing the chart object.
$(document).ready(function () {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [],
datasets: [{
label: ['Mensual'],
data: [],
backgroundColor: [
'rgba(137, 107, 255, 0.3)'
],
borderColor: [
'rgba(137, 107, 255, 1)',
],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
$.ajax({
type: "POST",
url: "Graficas.asmx/obtenerGrafica",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: function OnSuccess(response) {
items = response.d;
$.each(items, function (index, val) {
myChart.data.labels.push(val.Nombre);
myChart.data.datasets[0].data.push(val.Gastado);
nmbre.push(val.Nombre);
precio.push(val.Gastado);
});
},
error: function onError(error) {
console.log(error.d);
},
});
});
0👍
Add two arrays before your ajax call:
var nomreArr= [];
var gastadoArr= [];
Then populate them in the success function
and then assign them to the datasets
nomreArr.push(val.Nombre);
gastadoArr.push(val.Gastado);
myChart.data.datasets[0].data = gastadoArr;
myChart.data.datasets[0].labels= nomreArr;
myChart.update();
also your HTML should be like:
<canvas id="myChart" width="400" height="150"></canvas>
0👍
I had his same exact issue, and the only way I was able to fix it was by adding the following just before closing the document.ready block:
setTimeout(function() {
myChart.update();
},1000);
It’s less than ideal but that was the only thing I could do to consistently get the chart to render — call the “update” method after a 1 second delay.
Source:stackexchange.com