1๐
โ
So I approached this all wrong. The select.on.change()
should have been called outside the function, and when executing, call the showSuccessRate()
function.
Here is the working code:
$(document).ready(function(){
$('#selectTop')
.on('change', // When the user changed the select option, run this
function () {
$('#clisuccessrate-chart').remove(); //Remove the chart canvas (because it would have loaded when document ready)
$('div#clisuccessrate-container').append('<canvas id="clisuccessrate-chart" height="200"></canvas>'); // Add the canvas back into the html
showSuccessRate(); // Call the function to draw the chart
})// end onchange event
showSuccessRate(); // Make the Bar Chart when document is ready
function showSuccessRate(){ // Build Bar Graph
{var selectedOption = $('#selectTop').children('option:selected').val(); // Get the value of the option, use this value to set limit in PHP SQL Query
$.ajax("database/cliSuccessFail-filter.php", {data: {topSelect: selectedOption} ,method:'POST', success: function (data) {
console.log('The selected option value is: ' + selectedOption); // Log the value to check response
var mx_cli = [];
var mx_success = [];
var mx_failure = [];
var mx_attempts = [];
// ^ Declare empty array
for (var i in data) {
mx_cli.push(data[i].mx_cli);
mx_success.push(data[i].mx_success);
mx_failure.push(data[i].mx_failure);
mx_attempts.push(data[i].mx_attempts);
};
// ^ Populate the arrays
var csf_datasets = {
labels: mx_cli, // Assign label
datasets: [{
backgroundColor: '#007bff',
borderColor: '#007bff',
data: mx_success,
label: 'Successful'
},
{
backgroundColor: '#ced4da',
borderColor: '#ced4da',
data: mx_failure,
label: 'Unsuccessful'
}
]
};
var csf_options = {
maintainAspectRatio: false,
};
var csf_config = {
type: 'bar',
data: csf_datasets, // Bind dataset
options: csf_options, // Bind options
}
var $cliSuccessRateChart = $('#clisuccessrate-chart'); // Get the canvas ID
var myChart = new Chart($cliSuccessRateChart, csf_config); // Draw the chart
} }) // END POST
}
}// END FUNCTION showSuccessRate
}); //End document.ready()
Source:stackexchange.com