Skip to content Skip to sidebar Skip to footer

Jquery $(this) Problems With $.post()

So here's my code for when a user clicks a follow button: $('.follow_btn').click(function() { $(this).html(''); var us

Solution 1:

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.

Solution 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);
    });
});

Solution 3:

$(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)
    });
});

Post a Comment for "Jquery $(this) Problems With $.post()"