1

I have a problem with jQuery. I got two jQuery click events.

$('.btn-subscribe').click(function() {
                $.ajax({
                    type: 'POST',
                    url: '{{ path('subscribe') }}',
                    data: 'id={{ user.getId }}',
                    success: function(data){
                        if(data == 'subscribed') {
                            alert(data);
                            $('.btn-subscribe').removeClass('btn-subscribe').addClass('btn-unsubscribe').text('Отписаться');
                        }
                        else {
                            alert(data);
                        }
                    }
                });
            });

            $('.btn-unsubscribe').click(function() {
                $.ajax({
                    type: 'POST',
                    url: '{{ path('unsubscribe') }}',
                    data: 'id={{ user.getId }}',
                    success: function(data){
                        if(data == 'unsubscribed') {
                            alert(data);
                            $('.btn-unsubscribe').removeClass('btn-unsubscribe').addClass('btn-subscribe').text('Подписаться');
                        }
                        else {
                            alert(data);
                        }
                    }
                });
            });

On click, there is an ajax request. If the response is ok, i change button class (btn-subscribe to btn-unsubscribe and btn-unsubscribe to btn-subscribe). So when the button class changes it MUST call new button event but still, it is calling the event by old class.

How to fix this?

Tigran
  • 633
  • 4
  • 17
  • 26

1 Answers1

0

Use event delegation and register the listeners by class, not on the buttons themselves.

var buttons = $("button"); 
buttons.on("click", ".btn-subscribe", function (){//...etc});
buttons.on("click", ".btn-unsubscribe", function (){// ...etc});
user5325596
  • 2,310
  • 4
  • 25
  • 42