ok1ha
ok1ha

Reputation: 637

Add Class On Success

I'm looking to add a class on the element that is clicked on after POST was successful. For some reason, neither "this" nor "'add_favorite',this" is adding "favorited". Everything else works just fine.

Any ideas?

 $('.add_favorite').click(function(){
    expert_id = $(this).attr('data-expert-id');
    user_id = $(document.body).attr('data-user-id');

    //console.log(user_id);

    var data = {
        'expert_id' : expert_id,
        'user_id' : user_id
    }

    var url = "/submit-fav.php";

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function(data)
        {
            $(this).addClass('favorited');
        }
    });

    return false;
 });

Upvotes: 0

Views: 552

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

You need to keep a local copy of the original "this" in order to access it from within the scope of the success callback (which has a different "this").

 $('.add_favorite').click(function(){
    var  $add_favorite = $(this);
    var expert_id = $add_favorite.attr('data-expert-id');
    var user_id = $(document.body).attr('data-user-id');

    //console.log(user_id);

    var data = {
        'expert_id' : expert_id,
        'user_id' : user_id
    }

    var url = "/submit-fav.php";

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: function(data)
        {
            $add_favorite.addClass('favorited');
        }
    });

    return false;
 });

Notes:

  • I tend to prefix jQuery object variables with $
  • Your should declare all your local variables with var or they modify/pollute the global namespace.

Upvotes: 2

Related Questions