I've landed on a new messy code base without any testing available and I'm struggling for quite some time with this issue. I can't use any ES6 code, just plain old vanilla JS and jQuery.
The context: on a web page there are several pairs of inputs, the first input from the pair triggers the firstFunction()
on blur and the second input the secondFunction()
also on the blur event. As you can see from the sample code bellow, each function then calls another function, ajaxFunction()
which performs an AJAX request.
The goal: I want to be able to invoke the ajaxFunction()
only if there isn't another AJAX request in progress from a previous function invokement. The thing is that when it's run for the first time on a pair of inputs, a new row is created in the database and the request returns the ID of the row. So when it's called the second time, it will be an UPDATE in the database instead of an INSERT because of the ID. If the second call from the pair runs before the first one finished, I end up having two distinct rows in the database, which is not desired.
Example: if the user enters some text in the first input, then the firstFunction()
is triggered on blur, then he quickly moves to the second input and enters something so the secondFunction()
is triggered on blur, but it may be the case that the AJAX request from the firstFunction()
call hasn't been completed yet. So the AJAX call from the secondFunction()
should start only if the one from the firstFunction()
has been completed. The same logic applies for the case when the user starts typing in the second input and the in the first one.
Note: this aren't the only AJAX requests on the page, there are several others as well.
I've done some research and I feel like $.when()
is what I need, but it beats me when it comes to integrating it in this logic. I also thought about $.active
but it doesn't really help.
function firstFunction() {
// Some logic goes here then we call the AJAX function.
ajaxFunction(1, 2, 3);
}
function secondFunction() {
// Some logic goes here then we call the AJAX function.
ajaxFunction(4, 5, 6);
}
function ajaxFunction(param1, param2, param3) {
$.ajax({
method: "POST",
url: "https://website.localhost",
data: {
param1: param1
param2: param2
param3: param3
}
}).done(function() {
console.log('Done!');
});
}