user4175297 user4175297 - 16 days ago 7
Ajax Question

Allow jquery .One method to click again after Ajax call

I have a click that triggers payment. I'm using the .One method to disallow further clicking, but in case the payment comes back declined I'd like to re-enable the click for another try - one time again of course. And let this re-occur in case of another decline.

$(".pay").one("click", function(event){

...//payment code executes

});


Ajax

$.ajax({
...
success: function(data){
$('.pay').html(data); //comes back declined. Re-enable .one click again.
}

Answer

I would say, the best way is to:

  • Add a class.
  • Check if the class is present, then don't execute.
  • Fire the AJAX call.
  • Remove the class.

This is how disabling works.

This is better to use:

.addClass();
.removeClass();

Than writing entire function again and again, duplicating the code.


Update: If DOM manipulation is harder, or costlier, it is better to store the context sensitive values as a key-value pair using $.data(element, key, value); method and set the flag for execution.

Thanks to the Soviut and adeneo for their comments. :D


Example

added as per request...

$(".pay").on("click", function (event) {
  if ($(this).hasClass("stop"))
    return false;
  $(this).addClass("stop");
  // Other codes to follow.
});

$.ajax({
  //...
  success: function (data) {
    $('.pay').html(data)           //comes back declined. Re-enable .one click again.
             .removeClass("stop"); // remove the class that disables.
  }
});