Animated Ajax Record Deletion Using jQuery

I’m a huge fan of WordPress’ method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here’s how to achieve that functionality with jQuery javascript.

The PHP – Content & Header

The following snippet goes at the top of the page:

1. if(isset($_GET['delete']))
2. {
3.     $query = 'DELETE FROM my_table WHERE item_id = '.(int)$_GET['delete'];
4.     $result = mysql_query($query,$link);
5. }

The following is used to display the records:

01. $query = 'SELECT * FROM my_table ORDER BY title ASC';
02. $result = mysql_query($query,$link);
03. while($row = mysql_fetch_assoc($result))
04. {
05.     echo '<DIV class=record id="record-',$row['item_id'],'">
06.                 <A class=delete href="?delete=',$row['item_id'],'">Delete</A>
07.                 <STRONG>',$row['title'],'</STRONG>
08.             </DIV>';
09. }

The jQuery Javascript

01. $(document).ready(function() {
02.     $('a.delete').click(function(e) {
03.         e.preventDefault();
04.         var parent = $(this).parent();
05.         $.ajax({
06.             type: 'get',
07.             url: 'jquery-record-delete.php',
08.             data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
09.             beforeSend: function() {
10.                 parent.animate({'backgroundColor':'#fb6c6c'},300);
11.             },
12.             success: function() {
13.                 parent.slideUp(300,function() {
14.                     parent.remove();
15.                 });
16.             }
17.         });
18.     });
19. });

For every link, we add a click event that triggers the Ajax request. During the request, we transition the containing element to a red background. When the Ajax request returns a “success” response, we slide the element off of the screen.

Original:http://davidwalsh.name/animated-ajax-jquery

你可能感兴趣的:(animate)