tags:

views:

253

answers:

1

Hi, I am wondering why $(this) does not work after a jQuery ajax call.

My code is like this.

$('.agree').live("click", function(){  // use live for binding of ajax results
      var id=($(this).attr('comment_id'));
      $.ajax({
     type: "POST",
     url: "includes/ajax.php?request=agree&id="+id,
     success: function(response) {
      $(this).append('hihi');
     }
      });
      return false;
    });

Why doesnt the $(this) work in this case after ajax call? It would work if I use it before the ajax but no effect after.

+10  A: 

In a jQuery ajax callback, "this" is a reference to the options used in the ajax request. It's not a reference to a DOM element.

You need to capture the "outer" $(this) first:

$('.agree').live("click", function(){  // use live for binding of ajax results
      var id=($(this).attr('comment_id'));
      var $this = $(this);
      $.ajax({
        type: "POST",
        url: "includes/ajax.php?request=agree&id="+id,
        success: function(response) {
                $this.append('hihi');
        }
      });
      return false;
    });
Philippe Leybaert
+1 beat me to it (:
peirix
awesome! thanks you guys!
Scott
One more thing. Am I allowed to do traversing to it? Like closest?$this.closest('div').html('hihi');
Scott
Yeah, your new `$this` variable holds a jquery object, so you can treat it just like you would `$(this)`
peirix
great stuff, helped me as well
n00b