Ommadawn
Ommadawn

Reputation: 2730

Prevent fast button clicking for backend

I'm creating a web page where a button is located in it. When the user press the button, my Javascript uses AJAX to call my backend which asks my database and gets some pictures to put on the screen. It's something like this (pseudo-code):

// JS event
button.on('click', function(){
    // Here my AJAX calling
    $.post(callMyBackend, {
       foo: bar // Parameters
    }, function (responseText) {
       // Here goes more stuff...
    });
});

Everything works perfectly, but I want to prevent user doesn't abuse by clicking on the button too fast. So, if the user clicks 3 times very fast I would like that the calling to my backend would happens once (not 3 times) and return the results only for the last call (caution, the last one, no the first one!).

How could I resolve that?

Upvotes: 2

Views: 246

Answers (3)

gaetanoM
gaetanoM

Reputation: 42054

You may disable the button as first action. When you need or after a timeout you can enable again the button:

$('#button').on('click', function(){
    this.disabled = true;
    setTimeout(function(ele) {
        ele.disabled = false;
    }, 1000, this)
    return; // ......
    // Here my AJAX calling
    $.post(callMyBackend, {
        foo: bar // Parameters
    }, function (responseText) {
        // Here goes more stuff...
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Click Me</button>

Upvotes: 1

andy
andy

Reputation: 21

// JS event
button.on('click', function( this ){
if ( !this.hasAttribute( 'data-noclick' ) ) {
    // Here my AJAX calling
    this.setAttribute( 'data-noclick', 'true' );
    $.post(callMyBackend, {
       foo: bar // Parameters
    }, function (responseText) {
       // Here goes more stuff...
    this.removeAttribute( 'data-noclick' );
    });
});

Upvotes: 2

Vadim Hulevich
Vadim Hulevich

Reputation: 1833

You can add progress variable:

// JS event
var progress = false;

button.on('click', function() {
    if (progress) {
        return;
    }
    progress = true;
    // Here my AJAX calling
    $.post(callMyBackend, {
        foo: bar // Parameters
    }, function(responseText) {

        progress = false;
        // Here goes more stuff...
    });
});

of course i recommend you add js code for change style of your button e.x. "disabled"

Upvotes: 2

Related Questions