ReeseB ReeseB - 1 month ago 4
jQuery Question

Change icon using jquery on AJAX results

I have a list returned via AJAX after clicking on a link. In the list I have an font awesome link that is used to bookmark the list entry. The bookmarking is done via AJAX and this works fine, my database is update.

However, after the update I want to change the bookmark icon from

fa-bookmark-o
to
fa-bookmark
and add class
green
to make the icon green. This is not working. Code below.

HTML:

<a href="#" id="bookmark" title="Bookmark" bookmark_id="123"><i class="fa fa-bookmark-o" bookmark aria-hidden="true"></i></a>


SCRIPT

<script type="text/javascript">
$(document).on('click', '#bookmark', function(e) {
var bookmark_id = $(this).attr('bookmark_id');

$("#loaderIcon").show();
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>bookmark',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', bookmark_id},
dataType: 'json',
success:function(data){
if(data.status == 'X')
{
$(this).find('i').removeClass('fa-bookmark-o');
$(this).find('i').addClass('fa-bookmark');
$(this).find('i').addClass('green');
}
},
});
});
</script>


Fixed based on suggestions, I had to make another mod due to my class which allows me to change the font awesome icon on hover.

<script type="text/javascript">
$(document).on('click', '#bookmark', function(e) {
var bookmark_id = $(this).attr('bookmark_id');
var _this = $(this);

$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>bookmark',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', bookmark_id},
dataType: 'json',
success:function(data){
if(data.status == 'X')
{
$('#bookmark').removeClass('bookmark');
_this.find('i').removeClass('fa-bookmark-o').addClass('green');
}
},
});
});
</script>

Answer

this in the callback of the AJAX call is not the same as on the event handler.

There are multiple solutions, the simplest one is to store a variable in a closure and use that in the AJAX handler

$(document).on('click', '#bookmark', function(e) {
    var me = $(this);
    var bookmark_id = me.attr('bookmark_id');

    $("#loaderIcon").show();
    $.ajax({
        type: 'POST',
        url: '<?php echo base_url(); ?>bookmark',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', bookmark_id},
        dataType: 'json',
        success:function(data){
            if(data.status == 'X')
            {
                me.find('i').removeClass('fa-bookmark-o');
                me.find('i').addClass('fa-bookmark');
                me.find('i').addClass('green');
            }
        },
    });
  });

There are other improvements possible but I focused on the fewest changes to solve the problem

Other ways: Fat arrow functions, Function.bind

Comments