Reputation: 637
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
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:
$
var
or they modify/pollute the global namespace.Upvotes: 2