Reputation: 15037
I have a voting script, and it works fine when i vote one at a time, but when i vote on many items as fast as i can, some malfunction and stop, what can I do to prevent this? I only wanted to have one process at a time and wait for the process to finish before making another one.
$.ajax({
type: 'POST',
dataType: 'json',
url: 'vote/now',
timeout: 15000,
context: this,
data: {
'postid': $(this).attr('data-id'),
'vote': value,
'token': current_token
},
success: function(data,textStatus,jqXHR){
$points.fadeOut(500,function(){
$points.html(data);
$points.fadeIn(500);
});
},
error: function(){
$points.fadeOut(500,function(){
$points.html("Sorry, Try again");
$this.find('button').removeClass('clicked').attr('disabled',false);
$points.removeClass('busy');
$points.fadeIn(500);
});
}
});
Upvotes: 2
Views: 2321
Reputation: 230521
A common idiom (not just Javascript, but any language) for serializing network requests is to put arguments into a queue or a stack and then send one at a time.
Something like this (pseudo-code):
var argumentStack = [];
var isSending = false;
function serialSend(data) {
argumentStack.push(data);
trySend();
}
function trySend() {
if(!isSending && argumentStack.length > 0) {
var data = argumentStack.pop();
isSending = true;
$.ajax(data, success, error);
// in success and error handlers do this:
// isSending = false;
// setTimeout(trySend, 0);
}
}
Upvotes: 3
Reputation: 18588
you can show a loading
or spinning
image over the body to avoid next ajax call.
$.ajaxStart(function() {
$("img#loading").show();
});
$.ajaxComplete(function() {
$("img#loading").hide();
});
Upvotes: 1
Reputation: 121
Maybe inside the function the first line should be to deactivate the button or link that is calling the function and the the last line to activate it back. That way it would be impossible to call the function while it is still running...
Upvotes: 2
Reputation: 4894
Disable or hide the vote button as soon as it's clicked. Then, in the success and error functions of your AJAX request, enable or show it again.
Looks like you already do something like it in the error function.
Upvotes: 1