ToggleClass not working properly in ajax case

Below is my simple code where you want to tag code similar to the Gmail style.

$ (this) .toggleClass ('favorites');

the instruction above does not work. star does not turn yellow after receiving ajax response. but if you put the above statement outside the ajax block, it works. unable to understand why this is happening.

<html> <head> <style> .star { background-color: transparent; background-image: url('http://www.technicalkeeda.com/img/images/star-off.png'); background-repeat:no-repeat; display: block; height:16px; width:16px; float:left; } .star.favorited { text-indent: -5000px; background-color: transparent; background-image: url('http://www.technicalkeeda.com/img/images/star-on.png'); background-repeat:no-repeat; height:16px; width:16px; float:left; } span{ color: #2864B4; } </style> <script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script> <script> $(document).ready(function(){ $('.star').click(function() { var id = $(this).parents('div').attr('id'); $.ajax({ type: "post", url: "http://www.technicalkeeda.com/demos/bookmark", cache: false, data:{'bookmarkId': id}, success: function(response){ alert('response' +response); if(response=='true'){ $(this).toggleClass('favorited'); }else{ alert('Sorry Unable bookmark..'); } }, error: function(){ alert('Error while request..'); } }); }); }); </script> </head> <body> <div id="1000"><a href="javascript:void(0);" class="star" ></a><span>Php CodeIgniter Server Side Form Validation Example</span></div> <div id="2000"><a href="javascript:void(0);" class="star"></a><span>Live Search Using Jquery Ajax, Php Codeigniter and Mysql</span></div> <div id="3000"><a href="javascript:void(0);" class="star"></a><span>Voting system Using jQuery Ajax and Php Codeigniter Framework</span></div> </body> </html> 
+4
source share
3 answers

this in the ajax callback is not a .star element, it is a jqXHR object. Do it:

 $(".star").click(function () { var $this = $(this); /* snip */ if (response == 'true') { $this.toggleClass('favorited'); /* snip */ 
+5
source

$ (this) is no longer included in the scope of your answer. You can refer to it like this ...

 $('.star').click(function() { var elem = $(this); 

and then in the call back

 elem.toggleClass('favorited'); 
+2
source

To keep (almost all) the same, set the context for the ajax call:

$. Ajax ({context: this, success: function () {...}});

In another note, I just did, recommending something similar to another person regarding how to configure click events ...

 $('document.body').on('click', '.star', function () {....}); 

Provides you with the same functionality, improves performance, and automatically embeds any elements added or removed to a document with a star class.

0
source

All Articles