Reputation: 26212
I have a javascript function like this :
addGas = function(options){
var working = false;
$(document).ajaxSend(function(event, jqxhr, settings) {
if (settings.url == '/add_gas') {
working = true;
}
});
if(working) {
return;
}
$.ajax({
url: options.url,
data: options,
type: "POST",
success: function(data, textStatus, jqXHR){
$(".btn").addClass("added").text(" Added gas ").prepend("<i></i>");
},
error: function(jqXHR, textStatus, errorThrown){
}
});
}
So the way I test this is that I put 10 seconds sleep in my controller, and try to click the button again, and it makes a post request who is waiting, because my server can server one request at a time.
But I wanted not to send a post request if one is already running, alternatively alert a message if the request is already running.
How can I do that?
Upvotes: 2
Views: 1511
Reputation: 115541
Create a singleton handling its own state, this way you dont pollute the rest of the code with unused variables
gasHandlerBuilder = function(){
var ajaxInProgress = false;
return {
add_gas: function(options){
if(ajaxInProgress){ return; };
ajaxInProgress = true;
$.ajax({
url: options.url,
data: options,
type: "POST",
success: function(data, textStatus, jqXHR){
ajaxInProgress = false;
$(".btn").addClass("added").text(" Added gas ").prepend("<i></i>");
},
error: function(jqXHR, textStatus, errorThrown){
ajaxInProgress = false;
}
});
}
}
}
var gasHandler = gasHandlerBuilder();
gasHandler.add_gas(options);
Upvotes: 3
Reputation: 6299
You should use some flag, something like this :
var recieved = false;
$.ajax({
url: "http://first.call/",
})
.done(function( data ) {
// Do something with that data and enable the flag
recieved = true;
});
addGas = function(options){
var working = false;
$(document).ajaxSend(function(event, jqxhr, settings) {
if (settings.url == '/add_gas') {
working = true;
}
});
if(!recieved) {
return;
}
$.ajax({
url: options.url,
data: options,
type: "POST",
success: function(data, textStatus, jqXHR){
$(".btn").addClass("added").text(" Added gas ").prepend("<i></i>");
},
error: function(jqXHR, textStatus, errorThrown){
}
});
}
Upvotes: 0