Skip to main content

Bug Tracker

Side navigation

#2734 closed feature (invalid)

Opened April 22, 2008 11:26PM UTC

Closed September 28, 2010 11:53PM UTC

Last modified March 14, 2012 06:23PM UTC

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:
Blocked by: Blocking:
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
Attachments (0)
Change History (3)

Changed April 22, 2008 11:34PM UTC by jelly-bean comment:1

[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)

Changed May 11, 2008 11:20PM UTC by flesler comment:2

component: coreajax
type: enhancementfeature

Changed September 28, 2010 11:53PM UTC by dmethvin comment:3

resolution: → invalid
status: newclosed

The ajax method is already pretty complex, and this seems best implemented by a plugin.