1

So here's my code for when a user clicks a follow button:

$('.follow_btn').click(function() {
    $(this).html('<img src = "../assets/style_images/loading.gif">');
    var userId = $(this).attr('id');
    $.post('../assets/scripts/ajax_follow_parse.php', {
        userId: userId
    }, function(data) {
        $(this).html(data);
    });
});

It is quite happy to replace it with the loading gif as shown on line 2. But when it returns the data and replace it with the data returned on line 4.

How can I fix this?

Purag
  • 16,941
  • 4
  • 54
  • 75
Frank
  • 1,844
  • 8
  • 29
  • 44
  • Duplicate of [$(this) doesn't work in a function](http://stackoverflow.com/questions/7859558/this-doesnt-work-in-a-function), [$(this) object becomes undefined after a jquery post()](http://stackoverflow.com/questions/8422872/this-object-becomes-undefined-after-a-jquery-post) and many others. – Rob W Dec 30 '11 at 22:43

3 Answers3

9

Assign $(this) to a variable outside the $.post():

var $this = $(this);

Then, instead of using $(this) to add the data, use the variable we just created:

$this.html(data);

Looking at your code again, you could also do this:

$("#" + userId).html(data);

Since you already have the id of your element.

Purag
  • 16,941
  • 4
  • 54
  • 75
2

Inside $.post, this is no longer your element. You need to save it to a variable before $.post.

$('.follow_btn').click(function () {
    var $this = $(this); // Save this, so it can be used inside $.post
    $this.html('<img src = "../assets/style_images/loading.gif">');
    var userId = $this.attr('id');
    $.post('../assets/scripts/ajax_follow_parse.php', { userId: userId }, function(data) {
        $this.html(data);
    });
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

$(this) is out of context inside the $.post scope. You need to cache it into a variable and reuse it inside.

$('.follow_btn').click(function () {
    $this = $(this);
    $this.html('<img src = "../assets/style_images/loading.gif">');
    var userId = $this.attr('id');
    $.post('../assets/scripts/ajax_follow_parse.php', { userId: userId }, function(data) {
        $this.html(data); //$this not $(this)
    });
});
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308