I created a page where there the user selects a business and the page throws a barchart. The problem is that, the first time the use selects a business, the page shows the barchart correctly, but the second time the user selects a business, the page throw two charts with the past and new information. Here is my code.
<!DOCTYPE html>
<html>
<head>
<title>Estadisticas</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<select id="mySelect"></select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<div id="graph-container">
<canvas id="myChart"></canvas>
</div>
</body>
</html>
JAVASCRIPT
$(document).ready(function() {
/*
var numbers = [1, 2, 3, 4, 5];
var values = ["uno","dos","tres","cuatro","cinco"]
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ values[i] + '">' + numbers[i] + '</option>';
}
$('#mySelect').append(option);
*/
$.ajax({
url: "xx",
method: "GET",
success: function(data) {
var values = [];
var business = [];
var option = '';
for (var i in data) {
values.push(data[i].values);
business.push(data[i].Business);
option += '<option value="' + values[i] + '">' + business[i] + '</option>';
}
$('#mySelect').append(option);
},
error: function(data) {
console.log(data);
}
});
function getData(dato) {
$.ajax({
url: "zx",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var views = [];
for (var i in data) {
date.push("Date " + data[i].Date);
views.push(data[i].Views);
}
var chartdata = {
labels: date,
datasets: [{
label: 'Date',
backgroundColor: 'rgba(231,76,60 ,1)',
borderColor: 'rgba(231,76,60 ,1)',
hoverBackgroundColor: 'rgba(52,152,219 ,1)',
hoverBorderColor: 'rgba(52,152,219 ,1)',
data: views
}]
};
var ctx = $("#myChart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
}
$('#mySelect').change(function() {
console.log($(this).find(':selected').text());
console.log($(this).find(':selected').val());
getData($(this).find(':selected').val());
});
});
My webservices work, the only problem is at the moment the user selects another business, the page throws two charts with the past and new information.