I have an AJAX method that deletes a row from a database from a list of results from the database. Once the row has been successfully deleted, I want jQuery to fade out that row from the page.
After clicking on the delete button, the row is successfully deleted from the database, but the list item that is the parent of the button that was clicked does not fade out when searching for it using closest().
Here is my DOM:
<ul>
<li>
<div class="two columns alpha">
</div>
<div class="ten columns">
<ul>
<li><p></p></li>
<li><p></p></li>
</ul>
</div>
<div class="admin_buttons">
<div class="two columns">
<button type="submit" class="admin_button edit_event">Edit</button>
</div>
<div class="two columns omega">
<button type="submit" value="5" class="admin_button delete_event">Delete</button>
</div>
</div>
</li>
</ul>
Here is the jQuery:
$(document).on('click', '.delete_event', function() {
$.ajax({
type: 'POST',
url: 'php/deleteEvent.php',
cache: false,
data: {
id: $(this).val()
},
success: function(data) {
if(data === 'Error') {
alert('Error: event not deleted.');
}
else
{
$(this).closest("li").fadeOut('slow');
}
}
});
});
The reason it isn’t working as you expect is because the
thisyou get inside thesuccesscallback is not thethisyou have inside the click handler..ajax()has acontextoption for setting what gets passed to thesuccesscallback asthis. You can use that: