Setup
I have a form that uses a series of check boxes to determine a number selected on a page:
What it does is on selected, it makes a call off to a controller that will save the selection and return the new checked amount based on its current data.
The code looks like this
$('#myId').('click', '.selectorClass input', function() {
const inputCheckBox = this;
inputCheckBox.disabled = true;
$(inputCheckBox).addClass('disabled-checkbox')
$.ajax({
method: "POST",
url: "@(Url.Action<MyController>(c => c.MyEndPoint(Model.ItemId, null)))",
data: {
"boxWasChecked": inputCheckBox.checked
}
}).done(function (data) {
UpdateFields(inputCheckBox, data); //this would update the column footer and 'Total Quantity' field below
}).fail(function (data) {
// error check and handle here
}).always(function(data) {
inputCheckBox.disabled = false;
$(inputCheckBox).removeClass('disabled-checkbox')
});
});
This works great when selecting one at a time and even usually works when selecting multiple.
Problem
The issue comes when a user selects them very quickly and then sometimes the last request to finish wasn't the last one to come in/grab the data from the database on the controller side and therefore it brings back the wrong math for the total.
See image below where the math should be 11 (remember that it is adding the value of each box rather than number of boxes checked) but is reporting 6.
If I were to select the final check box, it would correctly report 12 because it has all the correct data in place for the call.
Part where I am stuck
I think I need to somehow make a list of ajax calls and then only call off a request if there is a request that is added after it OR all other requests infront of it have been completed. I don't know how to do this with ajax calls.
I have toyed around with promises/Fetch API and tried to get that working but could get the promise to add to the stack in Promise.all[myListOfAjaxCalls]
.
Summary of Code I am working towards
var listOfPromiseCalls = []
$('#myId').('click', '.selectorClass input', function() {
// my checkbox is clicked
listOfPromiseCalls.push(myAjaxCall/myPromise)
// Psudeo code
// begin request if it is the only one in the list
// else
// kick off other requests that are in existing list infront of it
// if other requests finish before another input is clicked, begin this request
});