Skip to content
Advertisement

jQuery click makes multiple AJAX calls

I’ve got multiple jQuery scripts working together. One binds the click actions to the elements, another handles the specific functions.

Although trying to stop multiple calls in different ways i can still fire off two calls by clicking really fast.

After the success call rebinds the action its also possible to double the number of calls each time it comes back, but this seems to be the consequence of being able to call it twice in the first place.

Any suggestions to make sure takeAction can only be called upon once?

Here’s a snippet of my code:

Action-click binder:

var actions = 
{
    pressed: false,
    bind: function()
    {
        $(".battleAction").off('click').one('click', function(event) {
            if (actions.pressed) return;
            actions.pressed = true;
            $(".battleAction").off('click');
            var idoption = $(this).attr('data-battle-option');
            battle.takeAction({    idoption: idoption   });
        });
    }
}

Battle functions:

var battle =
{
    takeAction: function( action )
    {
        battle.a = {
            idoption: null
        };

        $.extend( battle.a, action );

        $.ajax({
            url: "url/to/post",
            type: "post",
            data: { option: battle.a.idoption },
            dataType: "json",
            success: function(data) {
                actions.bind();
            }
        });
    }
}

And the HTML buttons that get the click event:

<button type="button" class="btn btn-default battleAction" data-battle-option="1">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>action 1</button>

<button type="button" class="btn btn-default battleAction" data-battle-option="2">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>action 2</button>

<button type="button" class="btn btn-default battleAction" data-battle-option="3">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>action 3</button>

The problem seems to be with re-assigning the click after the AJAX call. In that small timeframe I am able to launch two calls.

Advertisement

Answer

You can disable the button after clicking and re-enable it after AJAX call:

Action-click binder:

$(".battleAction").on('click', function(event) {
  $(this).prop("disabled", true);
  var idoption = $(this).attr('data-battle-option');
  battle.takeAction({    idoption: idoption   });
});

Battle functions:

var battle =
{
    takeAction: function( action )
    {
        battle.a = {
            idoption: null
        };

        $.extend( battle.a, action );

        $.ajax({
            url: "url/to/post",
            type: "post",
            data: { option: battle.a.idoption },
            dataType: "json",
            success: function(data) {
                $(".battleAction").prop("disabled", false);
            }
        });
    }
}
Advertisement