i need to pass $(this).data into success func in ajax. here is my code
var product_id = $(this).data("product_id");
var url = "{{ route('client.add_wishlist')}}";
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: {
product_id: product_id,
_token: "{{ csrf_token() }}",
},
success: function (data) {
$(this).addClass("wishlist-comp-saved");
},
});
But $(this).addClass('wishlist-comp-saved');
is not working inside success: function(data) {}
CodePudding user response:
$(this)
will change context when called. When inside of the success: function (data)
, $(this)
is not the same as it was inside of whatever is calling this $.ajax()
request.
For your issue, you simply have to set $(this)
as a variable before your $.ajax()
request, and reference it in the success: function()
:
var product_id = $(this).data("product_id");
var url = "{{ route('client.add_wishlist')}}";
var that = $(this);
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: {
'product_id': product_id
'_token': "{{ csrf_token() }}"
},
success: function(data) {
that.addClass('wishlist-comp-saved');
}
});