I have a simple .ajax
function that is triggered on a click event. The function triggers successfully, I'm having a hard time deleting the closest <tr>
tag to confirm deletion.
$('.delete_item').click(function () {
if (confirm('Delete this location?')) {
$.ajax({
type: "POST",
url: "/Admin/Location/Delete",
data: "{id: '" + $(this).attr('id') + "' }",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (msg) {
if (!msg) {
alert('There was an error deleting the location.');
return;
}
else {
$(this).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
}
},
error: function (msg) {
alert('error in ajax call');
},
});
}
return false;
});
Here is the mark-up
<tr class="class">
<td style="width:300px;">Rosana Square</td>
<td>24 Hours</td>
<td style="width:300px;">8555 Monrovia</td>
<td style="width:300px;">http://www.website.com</td>
<td style="width:50px; text-align:center;"><a href="/Admin/Location/Edit/13"><span class="glyphicon glyphicon-edit"></span></a></td>
<td style="width: 50px; text-align: center;"><a href="#_" id="13" class="delete_item"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
Inside of this ajax is this
no longer relevant? I'm not getting any errors. Can someone identify my error?
this
inside the ajax success call back is your problem since it doesn't refer to the element, instead it is jqXhr object. Try setting the context in the ajax settings or cached context.
$('.delete_item').click(function () {
if (confirm('Delete this location?')) {
$.ajax({
type: "POST",
url: "/Admin/Location/Delete",
data: "{id: '" + this.id + "' }",
contentType: "application/json; charset=utf-8",
context: this, //<--- Set the context
dataType: "text",
success: function (msg) {
if (!msg) {
alert('There was an error deleting the location.');
return;
}
else {
$(this).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
}
},
error: function (msg) {
alert('error in ajax call');
},
});
}
return false;
});
Or
$('.delete_item').click(function () {
if (confirm('Delete this location?')) {
var self = this; //Set it here
....
....
success: function (msg) {
if (!msg) {
alert('There was an error deleting the location.');
return;
}
else {
$(self).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
}
Also on a side note you can just use this.id
instead of $(this).attr('id')
Can always set a context variable for this
var that = $(this);
$.ajax({
..
..
success: function() {
that.closest('tr').css(