0

I realized the $(this) worked well outside the AJAX but not within the AJAX, can anyone help look at it to see what is wrong or what I can do?

$(function() {
    $(".add_friend").each(function () {
       var a=$(this).closest('div').find('#user').html();
       $.post("check_following.php", {username:a}, function(resp) {
        if (resp=='following') {
         $(this).hide();
        }     
      });
    });
});
Prathibha
  • 199
  • 13
atomty
  • 187
  • 2
  • 16
  • This logic makes me think you are repeating the id `user`. https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page – Taplar Jun 19 '18 at 21:28

2 Answers2

1

When you start a new function, the context of this will change. You have to cache the value somehow. Something like this is what I generally use for the same kind of situation:

$(function() {
  $(".add_friend").each(function() {
    var $this = $(this); // Cache it here.
    var a = $this.closest('div').find('#user').html();
    $.post("check_following.php", {
      username: a
    }, function(resp) {
      if (resp == 'following') {
        $this.hide();
      }
    });
  });
});
Prathibha
  • 199
  • 13
0

It is an scope issue here, every time you put a function inside another one in jQuery the scope is different

in the first level selector $(".add_friend").each(function() {..}) you are referencing to every iteration found for the selector, in this case an element with the class '.add_friend'.

On the second level, inside the ajax call $(this) no longer contains the element reference. You need to put the reference of the first level inside a variable so you can used on the another level scope.

It is also a good idea to use the .text() method instead of .html() so you get only the text inside the #user element, if you put, lets say an "<i></i>" tag inside the #user element, the selector $this.closest('div').find('#user').html(); will return "text <i></i>", but if you only need the text every time, it is safer to use .text(), you can use .trim() as well to remove any empy space from the string

$(function() {
    $(".add_friend").each(function () {
       var $this = $(this);
       var a= $this.closest('div').find('#user').text().trim();
       $.post("check_following.php", {username:a}, function(resp) {
        if (resp=='following') {
         $this.hide();
        }
        
      });

    });

});
Teobis
  • 825
  • 5
  • 12