JQuery AJAX call: $ (this) does not work after success

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

My code is as follows.

$('.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 doesn't $ (this) work in this case after ajax call? This will work if I use it before ajax, but without effect.

+3
source share
1 answer

In the jQuery callback, ajax "this" is a reference to the parameters used in the ajax request. This is not a reference to a DOM element.

First you need to grab the "outer" $ (this) :

$('.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;
    });
+11
source

Source: https://habr.com/ru/post/1717123/


All Articles