Mahesh
Mahesh

Reputation: 1333

Prevent repeated button clicks in a web page

I am currently building a Django application and there are two functionalities I have implemented so far.

1) Submit user data in a form

2) Read data from the google sheet and display it on the web page. there is a refresh button on this page when clicked the data in the DB gets updated.

Issue:- When the user clicks the submit button multiple times lets say 5 times, the same data gets inserted 5 times which is a huge problem. and in the case of the refresh button when clicked many times, I get an error like "duplicate key value violates unique constraint "

So, please suggest me a way to make the button not perform multiple times to prevent duplication and handle any corner cases.

Upvotes: 0

Views: 750

Answers (3)

You may want to destroy the eventListener when it has been clicked once.

function oneTimeEvent(element, eventType, callback) {
   element.addEventListener(eventType, function(e) {
   e.target.removeEventListener(e.type, arguments.callee);
   return callback(e);
 });
}

var btn = document.querySelector('button');
  oneTimeEvent(btn, 'click', function () {
  alert('Hello there! Did you click on me?');
});


<button>Click</button>

and when the user clicks on the refresh button, you can reload the page, and the eventlistener will be set again.

Upvotes: 1

Paolo
Paolo

Reputation: 853

Mahesh, Paulo made really good points but I would like to add something.

  1. Since you already have an onclick function for your AJAX, you can set that button to disabled=true after such event. BUT, remember that this is client-side and if I were you I wouldn't trust this solution as much.
  2. In combination with Solution #1, make use of model.objects.get_or_create() method. That way you can check if the same record is already in the DB, therefore avoiding multiple/repeating data.
# Example for Sol 2
# views.py

# Example model
from . models import Person

def insert_data(request):
    # Get whatever POST data you're trying to get from your AJAX.
    # I'll use name as an example

    post_name = request.POST.get('name')

    p, created = Person.objects.get_or_create(
        name=post_name,
    )

    # If there is no similar object in the table created = True
    # Else created = False
    # Validate

    if created == False:
      # Meaning there is a similar object existing
      # Return a response with a message saying object already exists?
    else:
      # Do whatever you want.

Upvotes: 0

Paulo Marques
Paulo Marques

Reputation: 119

Two simple steps:

  • Implement on javascipt client onclick="this.disabled=true,this.form.submit();"

  • Use HTTP Redirect to confirm or process the logic and display success message;

Upvotes: 0

Related Questions