Change icon using jquery on AJAX results
ajax, font-awesome, jquery
Solution
`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
Problem
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" class="bookmark" title="Bookmark" bookmark_id="12345"><i class="fa fa-bookmark-o"></i><i class="fa fa-bookmark"></i></a> ``` CSS ``` .bookmark:hover .fa-bookmark-o, .bookmark .fa-bookmark { color: #27ae60; display: none; text-decoration: none; } .bookmark:hover .fa-bookmark { color: #27ae60; display: inline; text-decoration: none; } ``` 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> ```