Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax and Preventing Double "submit"

I am dealing with a legacy application where they use [a] tags for many Ajax form "submits". If we were using [input] buttons we could just set the disable attribute of the [input] tag. But on hyperlinks disable is not part of the spec and is not consistent cross-browser.

We are looking for a simple solution for blocking the extra clicks on a hyperlink.

Note: we are using JavaScript with jQuery

like image 740
BuddyJoe Avatar asked Jul 06 '10 16:07

BuddyJoe


2 Answers

womp's solution is a very very thorough way to go about this.

However, if you want something a little simpler, I would probably implement a semaphore. Simply set a "submitting" flag, and test to see if the semaphore is set when the user clicks the link. You can do this by setting the flag on the DOM object itself, or use a global boolean.

$('#link').each(function() {
    this.submitting = false;
}).click(function() {
    if (!this.submitting)
    {
        this.submitting = true;
        var self = this;
        $.ajax({
             success: function() {
                 self.submitting = false;
             },
             error:  function() {
                 self.submitting = false; // make sure they can try again
             }
        });
    }
});

I've obviously shortened the $.ajax call, but I think you get the point.

Edit: Er... actually, forgot the most important part. The if (!submitting).

like image 76
Ryan Kinal Avatar answered Nov 04 '22 22:11

Ryan Kinal


In your "click" handler either return false or prevent default -

$('#target').click(function(e) {
  e.preventDefault();
  alert('Handler for .click() called.');
});

$('#target').click(function(e) {
  alert('Handler for .click() called.');
  return false;
});

Hmm... to only allow the button to be pressed once (throughout the life of the page) then maybe utilize .data() -

http://api.jquery.com/data/

Or toggle an attribute.

like image 40
Kris Krause Avatar answered Nov 04 '22 20:11

Kris Krause