I have a scatted chart (chart.js) and a form-control for user to change the time period of the chart. When user selects different option in form-control, an ajax script is invoked to get a new set of data from controller. And it works fine at a first glimpse. The chart is dynamically reloaded and new data is showed. But when I roll a mouse pointer over a chart, it shows, that there are in fact two charts in the same place. And browser tries to show once a new one and once an old one. It looks strange. What do I do wrong? I wish to have only a new chart after refresh. Here's my html and script code:
@model LivtronDb.Device
@{
ViewData["Title"] = "Chart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<h1>@ViewData["Title"] @Html.DisplayFor(model => model.Name)</h1>
<hr />
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"></label>
<select class="form-control" value=1 id="chartParameterDays">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="7">7 days</option>
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div>
<div scope="row" colspan="2" class="col-8">
<div id="chartContainerT" class="containerT">
<canvas id="myChartT"> </canvas>
</div>
</div>
</div>
</div>
@section Scripts
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<script>
function GenerateRuntimeGraph(id, days) {
$.ajax({
type: "POST",
url: `/Devices/ChartData?id=${id}&days=${days}`,
success: function (chData) {
let chDataObj = JSON.parse(chData);
var options = {
type: 'scatter',
data: {
datasets: [{
label: "Temperatura",
backgroundColor: "rgba(196, 93, 105, 0.3)",
showLine: true,
data: chDataObj.dataListT
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: { unit: 'hour' },
gridLines: { display: false },
display: true,
scaleLabel: { display: false, labelString: '' }
}],
yAxes: [{
ticks: { min: chDataObj.dataChartBoudaries.minT, max: chDataObj.dataChartBoudaries.maxT }
}]
}
}
}
var ctx = document.getElementById('myChartT').getContext('2d');
var chartTHolder = new Chart(ctx, options);
},
"error": function (data) {
alert("Sorry, error!");
}
});
}
//run when list changed
$("#chartParameterDays").change(function () {
GenerateRuntimeGraph('@Model.Id', $('#chartParameterDays').val());
});
</script>
<script>
//loaded on open
GenerateRuntimeGraph('@Model.Id', $('#chartParameterDays').val());
</script>
}