Search code examples
ajaxjqueryclosuresjquery-callback

$(this) object not available in AJAX callback


Possible Duplicate:
$(this) inside of AJAX success not working

I am using one button click in which an ajax call back is there. If it return success I want to add a class to my button like $(this).addClass('abc'); but of no use. $(this) is not working in AJAX. What is the alternate method to do this, because there are several same blocks.


Solution

  • Once you are inside of the AJAX callback this does not point to your button any more (google "JavaScript closures and this" for more).

    You need to save the reference to the current this into a variable and then use that to add classes. Something like this:

    $( '#button' ).click ( function () {
      var $this = $( this );
      $.get (
        'url',
        function ( data ) {
          $this.addClass ( 'abc' );
        }
      );
    } );