jQuery : Why $(this) doesn't work with this ajax?

Hi, I’m trying to make a basic like-unlike system using ajax.

$('.like').on('click', (function (a) {
    a.preventDefault();
    ($(this).text() === "Undo") ? $(this).text("Like") : $(this).text("Undo");
    var thisid2 = $(this).attr('id');
    var thisid3 = thisid2.slice(4);
    if ($(this).text() == "Like") {
        $.post(
            "/includes/contentpages/process.php",
            {
                reverselike: thisid3
            });
        alert("You liked it");
    } else {
        $.post(
            "/includes/contentpages/process.php",
            {
                likeable: thisid3
            }, function (data) {
                $(this).parent().find('.bottom-right2').html(data); // problematic part is here
            });
        alert("You unliked it");
    }
}));

If I use $(‘.bottom-right2’).html(data) instead of $(this), it works but I don’t want this since I only want to target the clicked one.

I couldn’t solve it.

The scope of $(this) in the problematic part is the anonymous function returning the data (or maybe the $.post I can’t remember).

After a.PreventDefault(), do this then refer to it instead.

$('.like').on('click', (function (a) {
    a.preventDefault();
    var $self = $(this);
    ($self.text() === "Undo") ? $self.text("Like") : $self.text("Undo");
    // etc.

That way you can use it throughout the rest of the code fine. $self is not a keyword, I just added the $ to denote to the programmer that it’s already a jQuery variable. You could also use var self = this then refer to it using $(self) later on.


Another thing, the a doesn’t really make much sense to me. I see and use .click(function (e) {}) where e stands for event. The jQuery docs use the whole word event and MDN use evt. Not really a big deal, but a doesn’t seem to make much sense. :smile:

1 Like

It worked, thanks. I learned something new.

1 Like

if you want to use the button’s this inside the AJAX handler you can set the context parameter.

just use

var thisid2 = this.id;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.