0

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');
                }
            })
        });
    });

3 Answers 3

1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Hello, that's the problem, I can't figure out how to remove the handler on success.
1

You can add to your success function something like: $this.data('isConfirmed', true);

And then in your click handler start by checking for it. If it's true, redirect the user to the next page.

$(".confirm-button").click(function (b) {
    b.preventDefault();
    var $this = $(this);

    if ($this.data('isConfirmed')) {
        ... redirect code ...
    }
    else {
        ... your regular code ...
    }
}

Comments

1

You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.

See http://api.jquery.com/on/

$(document).ready(function() {
  $('.js-confirm').click(function(){
    alert('Confirmed!');
    $(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
  });
  
  $(document).on('click', '.js-redirect', function(){
    alert('Redirecting');
  });
});
<button class="js-confirm">Confirm</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.