I have implemented some charts on my view to show stats, but it don't load correctly, only after reloading the page 2, 3, 4 or 5 times...
First, i make a ajax call to get data, and then i use the result do load and create chart.js chart.
<script>
var bSt = [];
var lSt = [];
var cSt = [];
var mainStatsChart = {};
var horizontalBarChartData = {};
var percentChart = {};
var color = Chart.helpers.color;
$.ajax({
url: '@Url.Action("GetStats", "Toons")',
data: { id: @Model.ToonID },
type: 'POST',
success: function (data) {
bSt = data.baseStats;
lSt = data.legStats;
cSt = data.criticalStats;
CreateData(bSt, lSt, cSt);
}});
function CreateData(baseStats, maxLevelStats, criticalStats)
{
mainStatsChart = {
labels: ['Strenght', 'Agility', 'Stamina', 'Intelligence'],
datasets: [{
label: 'Base Stats',
backgroundColor: window.chartColors.purple,
data: [
baseStats[0],
baseStats[1],
baseStats[2],
baseStats[3]
]
}, {
label: 'Level 70 Gear 11 Stats',
backgroundColor: window.chartColors.yellow,
data: [
maxLevelStats[0],
maxLevelStats[1],
maxLevelStats[2],
maxLevelStats[3]
]
}]
};
percentChart = {
labels: ['Critical Chance %', 'Critical Value %'],
datasets: [{
label: 'Base %',
backgroundColor: window.chartColors.purple,
data: [
criticalStats[0],
criticalStats[1]
]
}, {
label: 'Level 70 Gear 11 %',
backgroundColor: window.chartColors.yellow,
data: [
criticalStats[2],
criticalStats[3],
]
}]
};
}
window.onload = function () {
var ctx = document.getElementById('chStats').getContext('2d');
window.chartOne = new Chart(ctx, {
type: 'bar',
data: mainStatsChart,
options: {
title: {
display: false
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}]
}
}
});
var ctx2 = document.getElementById('chPercent').getContext('2d');
window.charTwo = new Chart(ctx2, {
type: 'horizontalBar',
data: percentChart,
options: {
responsive: true,
title: {
display: false,
text: 'Chart.js Horizontal Bar Chart'
},
scales: {
yAxes: [{
stacked: true,
}]
}
}
});
};
</script>
But it don't work properly, the chart shows up without data, only the chart design load.
EDIT: Data returned from Controller
int[] baseStats = { stats.Strength.Value, stats.Agility.Value, stats.Stamina.Value, stats.Intelligence.Value };
int[] legStats = { stats.Strength70.Value, stats.Agility70.Value, stats.Stamina70.Value, stats.Intelligence70.Value };
int[] criticalStats = { stats.CriticalChance.Value, stats.CriticalChance70.Value, stats.CriticalValue.Value, stats.CriticalValue70.Value };
return Json(new { baseStats, legStats, criticalStats, JsonRequestBehavior.AllowGet });