Bug Tracker

Opened 15 years ago

Closed 12 years ago

Last modified 11 years ago

#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:
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

Change History (3)

comment:1 Changed 15 years ago by jelly-bean

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

comment:2 Changed 15 years ago by flesler

Component: coreajax
Type: enhancementfeature

comment:3 Changed 12 years ago by dmethvin

Resolution: invalid
Status: newclosed

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

Note: See TracTickets for help on using tickets.