I am trying to change some old code which uses onclick so that I an use the $(this). The problem is that $(this) is not working when inside the success. Is there anyway to do this without setting it as a var.
$('.addToCart').click(function() {
$.ajax({
url: 'cart/update',
type: 'post',
data: 'product_id=' + $(this).attr("data-id"),
dataType: 'json',
success: function(json) {
if (json['success']) {
$(this).addClass("test");
}
}
});
});
Problem
Inside the callback,
thisrefers to thejqXHRobject of the Ajax call, not the element the event handler was bound to. Learn more about howthisworks in JavaScript.Solutions
If ES2015+ is available to you, then using an arrow function would probably be the simplest option:
You can set the
contextoption:or use
$.proxy:or keep a reference to the value of
thisoutside the callback:Related