jQuery Ajax delete
Removing contents with Ajax is a useful tool to have in any web designers kit. Using a few lines of jQuery we can remove a div and simultaneously remove a record from the database with Ajax. In the download and demo you’ll see a small red cross to the right of each comment. Clicking the cross will remove the comment div with a slide up animation which will remove the div.
The Code
We start by writing the dom ready function to simply hide our loading message div which is used as a visual representation to the user when we go to delete a comment.
$(document).ready(function() { $('#load').hide(); });
The next block of code is what essentially does the hard work. we have a .click function to start with that when run fades in the ‘#load’ div to show the user that we’re deleting the item.
We then set the variable ‘commentContainer’ which is set to represent the parent element to ‘.delete’ which is the div ‘.box’ as show in the image below.
var commentContainer = $(this).parent();
The variable ‘id’ is then set with the value of the delete button id which would could be the id of the row in the database that you want to delete. This is then posted to the page delete.php. once the Ajax request has been made and a response has been acknowledged we then slide up and remove the div ‘.box’ and fade out the loader. Finally ‘return False;’ is added to the end of the function in order to stop the page from refreshing as we are using an ‘a tag’.
$(function() { $(".delete").click(function() { $('#load').fadeIn(); var commentContainer = $(this).parent(); var id = $(this).attr("id"); var string = 'id='+ id ; $.ajax({ type: "POST", url: "delete.php", data: string, cache: false, success: function(){ commentContainer.slideUp('slow', function() {$(this).remove();}); $('#load').fadeOut(); } }); return false; }); });
You might also like
Tags
accordion accordion menu animation navigation animation navigation menu carousel checkbox inputs css3 css3 menu css3 navigation date picker dialog drag drop drop down menu drop down navigation menu elastic navigation form form validation gallery glide navigation horizontal navigation menu hover effect image gallery image hover image lightbox image scroller image slideshow multi-level navigation menus rating select dependent select list slide image slider menu stylish form table tabs text effect text scroller tooltips tree menu vertical navigation menu