Reputation: 13287
I'm starting to integrate some jQuery calls in my Classic ASP pages but want to prevent the user from clicking buttons multiple times and sending multiple server queries. What's a good practical way to do that?
Upvotes: 0
Views: 1446
Reputation: 9719
It really depends what your .ajax()
call's look like.
For example you could disable the button which sends the .ajax()
call using the beforeSend
function. Then re-enable it when you either get success
or an error
:
$('#test').click(function() {
var obj = $(this);
$.ajax({
beforeSend: function() {
toggleBtn(obj);
},
url: '/echo/html/',
data: 'whatever',
success: function(data) {
// Do whatever with data....
alert("While an alert is showing, the JS is paused, look at the button. After clicking ok, its going to be enabled.");
toggleBtn(obj);
},
error: function() {
// Do whatever with the error.....
// Re-enable the button, you need to do this, otherwise on an error
// the user couldn't try again without reloading the page.
toggleBtn(obj);
}
});
});
See a demo here
Use a simple wraper function to allow you to re-use the code:
function toggleBtn(obj) {
if (obj.attr('disabled') == true) {
obj.attr('disabled', false);
}
else {
obj.attr('disabled', true);
}
}
Alternatively you could attach a .ajaxStart()
and .ajaxStop()
to the click event:
$('#test').click(function() {
$.ajax({
url: '/echo/html/',
data: 'whatever',
success: function(data) {
// Do whatever with data....
alert("While an alert is showing, the JS is paused, look at the button. After clicking ok, its going to be enabled.");
},
});
}).ajaxStart(function() {
toggleBtn($(this));
}).ajaxStop(function() {
toggleBtn($(this));
});
See a demo here
Another way would be to disable ALL ajax call's whilst one is happening. To do this, you could give all your ajax buttons a class. Then attach the .ajaxStart()
and .ajaxStop()
to the document:
$(document).ajaxStart(function(e) {
toggleBtn($('.ajax'));
}).ajaxStop(function() {
toggleBtn($('.ajax'));
});
See a demo here
NOTE: the alert is just to pause the execution of the JS so you can see the button is actually disabled, otherwise it would happen too quickly to see whats happening.
Of course you could also add the option async: false,
, which means the script will pause till it get's a result.
Upvotes: 2
Reputation: 1497
http://jquery.malsup.com/block/ - is a very nice jquery plugin that can be used for exactly this.
Or you can use the events available in jquery.
and
You could use these two to create a function of your own that you fires when an ajax call is made.
Upvotes: 0