Categories
Uncategorized

$(this) is not working in success method of ajax

I recently came to know that the $(this) does not work in the success/error method of ajax.

I was trying to remove a div on success of some ajax call, and it just didn’t work. But when I tried using jsFiddle suprising it worked, below is the jsfiddle.

Jsfiddle Link : http://jsfiddle.net/H5sDC/39/

So I posted this as a question on Stackoverflow.

And the answer was pretty simple, use the context:this property.

Example :

$('.doneBtn').live('click', function () {
var taskId = $(this).attr("data-taskid");
$.ajax({
url: '/Task/TaskCompleted/?strTaskId=' + taskId,
type: "POST",
context: this,
success: function (data) {
$(this).parent().parent().closest("div").remove();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error');
}
});
});