Modify ↓
Ticket #2734 (closed feature: invalid)
jQuery.ajax({ lock: 'string identifier' }) to prevent duplicate submissions
| Reported by: | jelly-bean | Owned by: | |
|---|---|---|---|
| Priority: | major | Milestone: | 1.2.4 |
| Component: | ajax | Version: | 1.2.3 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
I would like to suggest a new 'lock' parameter for jQuery.ajax. I created one myself and I use it all the time. See below for definition and usage example:
// definition
var myAJAX = {
// AJAX locking system prevents simultaneous/duplicate requests.
ajax_locked: {},
ajax_lock: function(id) {
if (myAJAX.ajax_locked[id]) {
alert('Only click once, please.');
return false; // cannot obtain lock; already locked
}
else {
myAJAX.ajax_locked[id] = true; // lock
return true;
}
},
ajax_unlock: function(id) {
myAJAX.ajax_locked[id] = null;
},
ajax: function(o) {
if (o.lock && !myAJAX.ajax_lock(o.lock)) return;
return jQuery.ajax({
type: 'POST',
url: o.url,
data: o.data,
dataType: o.dataType,
timeout: 30000, // ms
beforeSend: o.beforeSend,
success: o.success,
error: o.error,
complete: o.complete
});
},
}
// usage example
myAJAX.ajax({
lock: 'create_task',
data: jQuery('form').serialize(),
success: function() { alert('yay!'); }
});
// works even better when combined with:
// http://dev.jquery.com/ticket/2688
// like so...
myAJAX.ajax({
lock: 'delete_task',
beforeSend: function() {
return confirm('Are you sure');
},
data: 'id='+id,
success: function() { alert('done.'); }
});
// because then the confirmation dialog doesn't appear if it's already going...
// this assumes you are being nice to the user and displaying some sort of AJAX spinner graphic
Change History
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.
Note: See
TracTickets for help on using
tickets.

[17:32] ThrushAAX: jelly-bean: I would simply remove the click or whatever event so its impossible to click again [17:33] jelly-bean: ThrushAAX: not a bad idea; i've done that before as well as setting the disabled attribute on an element. this just makes it easy because you can limit it on a per-element level or a regional level (e.g. all delete events) or a global level (e.g. all events, assuming you use the same lock identifier)