Milano Milano - 5 months ago 6
Ajax Question

Change behavior of button using AJAX

I'm trying to figure out how to change behaviour of a button using AJAX.

When the button is clicked, it means that

user
confirmed order recently created.
AJAX
calls
/confirm-order/<id>
and if the
order
has been confirmed, I want to change the button to redirect to
/my-orders/
after next click on it. The problem is that it calls again the same
JQuery
function. I've tried already to remove
class="confirm-button"
attribute to avoid
JQuery
again but it does not work. What should I do?

It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.

$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;

$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});

Answer

The event handler will be still attached to the button, so this will run again:

b.preventDefault();

which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:

$(".confirm-button").off('click');

or more shortly:

$this.off('click');
Comments