views:

170

answers:

3

Hi guys, I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.

I googled and googled and found a few scripts, but none of them seem to be sufficient.

How can I prevent these duplicate entries from occurring using javascript or preferably jQuery?

Thanx in advance!

+5  A: 

This should do the trick:

$("form").submit(function() {
   $(":submit", this).attr("disabled", "disabled");
});

No JQuery?

Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.

Sarfraz
I do have a unique piece of data that I can check, each id_number is unique, how would I go about implementing a check like that?
+5  A: 

How about disabling the button on submit? That's what I do. It works fine.

$('form').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

Disclaimer:
This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.

I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.

Bill Paetzke
I'll give it a go, thanx.
Javascript is only part of the solution here, you should be checking the database as well to check if data has just been entered. If you have a unique piece of data you can check this is the best way, but another method is to have a timestamp on the data and check if that user has added anything in a short period of time. However this would depend on the application on what it is that you are adding.
dnolan
I do have a unique piece of data that I can check, each id_number is unique, how would I go about implementing a check like that?
@kielie is id_number an identity field?
dnolan
No it isn't, it's a normal field entered by the user, but each one is unique.
@dnolan, You're right on. I added a disclaimer to my answer.
Bill Paetzke
@kielie in that case, you should do a quick select prior to your insert to see if that unique id already exists, if so, return an message to the user to cease being an impatient so and so
dnolan
A: 

Here is bit of jQuery that I use to avoid the double click problem. It will only allow one click of the submit button.

$(document).ready(function() {
  $("#submit").one('click', function() {
  });
});
Jim Schmehil
Thanx, I'll give it a go!