0

I am trying to change the icon using the jquery and ajax call. I have this function that let any logged in user like or unlike the image. So to do that I am using jquery's click event to get the URL of the function and then using ajax I am trying to change the icon. Here is the detailed code:

<a href="#" class="pull-right nogo" 
  data-url="{% url 'favorite' song.id %}"><i class="fa fa-heart-o"></i></a>
$('.nogo').on('click', function () {
    var url = $(this).attr('data-url');
    console.log(url);
    $.ajax({
        type: "get",
        url: url,
        success: function () {
            icon = $(this).find("i");
            icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down");
            console.log('done');
        }
    });
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Baked Pro
  • 123
  • 1
  • 4

2 Answers2

0
$('.nogo').on('click', function () {
    var url = $(this).attr('data-url');
    console.log(url);
    var _this = $(this);
    $.ajax({
        type: "get",
        url: url,
        success: function () {
            icon = _this.find("i");
            icon.toggleClass("fa-heart fa-heart-o");
            console.log('done');
        }
    });
});
Jaimin Rlogical
  • 256
  • 1
  • 11
0

As Taplar mentioned: there is a probably a problem with 'this'

Can you try this?

$('.nogo').on('click', function (e) {
    var url = $(this).attr('data-url');
    // Uses the click event to get where clicked.
    // And create a jQuery object of it.
    var target = $(e.target)
    $.ajax({
        type: "get",
        url: url,
        success: function () {
            target.toggleClass("icon-circle-arrow-up icon-circle-arrow-down");
            console.log('done');
        }
    });
});
Wimanicesir
  • 4,606
  • 2
  • 11
  • 30