Treehouse

Animated AJAX Record Deletion Using jQuery

By on  

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:

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

The following is used to display the records:

$result = mysql_query('SELECT * FROM my_table ORDER BY title ASC',$link);
while($row = mysql_fetch_assoc($result)) {
	echo '
Delete ',$row['title'],'
'; }

The jQuery JavaScript

$(document).ready(function() {
	$('a.delete').click(function(e) {
		e.preventDefault();
		var parent = $(this).parent();
		$.ajax({
			type: 'get',
			url: 'jquery-record-delete.php',
			data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
			beforeSend: function() {
				parent.animate({'backgroundColor':'#fb6c6c'},300);
			},
			success: function() {
				parent.slideUp(300,function() {
					parent.remove();
				});
			}
		});
	});
});

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.

How would you use this? Share!

ydkjs-1.png

Recent Features

  • Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome,...

Incredible Demos

  • Create a Twitter AJAX Button with MooTools, jQuery, or Dojo

    There's nothing like a subtle, slick website widget that effectively uses CSS and JavaScript to enhance the user experience.  Of course widgets like that take many hours to perfect, but it doesn't take long for that effort to be rewarded with above-average user retention and...

  • Disable Autocomplete, Autocapitalize, and Autocorrect

    Mobile and desktop browser vendors do their best to help us not look like idiots by providing us autocomplete, autocorrect, and autocapitalize features.  Unfortunately these features can sometimes get in the way;  we don't always want or need the help they provide.  Luckily most browsers allow...

Discussion

  1. I’ve never played with WordPress much, so I’ve never this; very nice, I like. I’m going to implement this into my control panel for comment management. I’ll add a little functionality in that there will be two links, one to approve, and one to reject, and the approval action will turn the comment green as it slides off the screen.

    Also, have been reading your site mostly in my RSS reader recently. Hadn’t seen the new Facebook-esque theme you have, nice look.

  2. I dont know jQuery, but could you apply the click event to the a.delete collection instead of iterating it with each() ?

  3. Jeferson Koslowski

    As EmEhRKay pointed out, u dont need to do the .each() thing.

    $('a.delete').click() will bind a click event to the returned collection of your selector.

  4. Code updated to remove .each(). Thanks guys!

  5. BeN

    on the php part i recomend this line:

    $query = ‘DELETE FROM my_table WHERE item_id = ‘.intval($_GET['delete']);

  6. BeN

    A little error on php line 3 there’s no “int” functionon php… i recomend

    $query = ‘DELETE FROM my_table WHERE item_id = ‘.intval($_GET['delete']); //to obtain the integer value of delete and also prevent SQL Injection

  7. @BeN: I’m typecasting $_GET['delete'] to an integer. Essentially I’m doing the same thing you’re recommending, just in a different way.

  8. Hey David
    I like your take on this. Is it possible to write this so that (just like wordpress), when you delete a record, it stays deleted. I noticed the recors re-appears when the page refreshes. (Understanding that you cant allow for actual record deletion on the demo)

    Thx
    Anthony
    465media

  9. @Jesus DeLaTorre: This would obviously be put behind a password-protected area. Your concern is valid but, in my opinion, easily avoidable.

  10. Its not just that it needs to be behind a password protected area, there needs to be something else than a simple click for to you delete/modify data from the database.

    Say you were already passed the protected area and you had your cookies all set. You get an email and you open it. It contains this.

    <img src=”http://davidwalsh.name/dw-content/jquery-record-delete.php?delete=3” />

    Since you are already logged, it will verify your cookies and go ahead and complete this request. Your record just got deleted.

    vBulletin doesnt have this issue. vBulletin forces “An are you sure?” type page. I dont think there is a way to do this and keep this special effect.

    But for this to work, the attacker will need to know how to create the delete link. This is the only thing I think will stop the attack in custom apps but I don’t think its good safegaurd.

    I’m by no means knocking on this tutorial or anything, I think it’s great. I was just making sure people knew the CSRF attack that can come from it.

  11. While I understand Jesus’ concerns, hopefully the programmer would at the least employ the double cookie check method described here

    where, along with the request vars, you send a token and the session id to verify the request

  12. Ammonkc

    Nice effect. I really like the way wp does this also. Do you have a way to accomplish the same effect with prototype.js? This would go really nicely in my current project, but I’m using prototype and I’m too deep into the project to switch to jQuery at this point.

    Thanks

  13. Nice Effect….

  14. AFRC

    What if we want to add a modal confirmation with jQuery UI Dialog?
    I tried but with no sucess.

    Any tips?

    Thanks for the nice script.

  15. Looks great. If I would suggest one minor tweak to suit me personally, it would fade to red, then fade to invisible (i.e. disappear), and then the rows would slide up to fill up the space. I think this would look even cooler. Of course I’m sure when I learn jQuery I’ll be able to tweak it to do that myself. ;)

  16. Implementing the jQuery UI Modal box would be a great enhancement to this script.

    It would add a layer of security as discussed above and make the application more user friendly.

  17. Salih Gedik

    Very Nice (:

  18. Just finished implementing it. Works perfectly, thanks!

  19. jasons

    Is there a way to do this using a POST instead of a GET?

  20. @jasons: Yes, just change the “get” references” to “post” in the jQuery javascript and PHP.

  21. Very Useful, thanks!!!

  22. jasons

    If you do it as a POST, could you have it take form input fields name/values to pass to the php by telling jquery the form name or form id and it would pass what ever is in the form, instead of listing all the variables name and values in the jquery?

  23. cmdr

    The script is good but the effect works does not work the same manner on tag.
    As some body try it on a tag ?

  24. Ben

    Ooo…Ive been trying to get this to work for ages, finally Ive worked this out. I didn’t realise I had to define id=”record-” within a div an a tag. Hehe.

    Thanks for this.

  25. deepblue_tiano

    very nice effect.. is that possible to implement in check box?

  26. ben

    Awsome effect. I noticed you are doing this with the parent element being a div tag. Could you do this with a table row?

    <tr>
    <td>title</td>
    <td><a>delete</a></td>
    </tr>

  27. Rob

    This is cool so thanks for sharing.
    I have a few suggestions to make it more complete and usable;
    1) confirm the delete
    2) allow multiple selections to be deleted

  28. AFRC

    To get this working on tables, just add

    var parent = $(this).parent("td").parent("tr");

    instead of

    var parent = $(this).parent();

    Don’t forget to add the id to tr.

    Does anyone can make this working with jQuery UI Dialog modal confirmation or any simple confirmation?

    I tried to add a simple onclick confirm return true or false, but it always returns true.

  29. nice, I will try

  30. Holo

    BenN,

    (int) is not a function, it is called typecasting, and is perfectly valid in php.

  31. Hello guys!
    this implementation is fantastic (sorry for my bad english)

    I qote Rob

    1) confirm the delete
    2) allow multiple selections to be deleted

  32. Lionel

    can this be used to remove entire tr ?

  33. *lionel
    Yes, AFRC says

    AFRC says:

    To get this working on tables, just add

    var parent = $(this).parent(“td”).parent(“tr”);

    instead of

    var parent = $(this).parent();

    Don’t forget to add the id to tr.

    Does anyone can make this working with jQuery UI Dialog modal confirmation or any simple confirmation?

    I tried to add a simple onclick confirm return true or false, but it always returns true.

  34. BMiller

    A few people mentioned were looking for a modal popup solution to round out the demo so here are the changes required to implement it with the addition of the JQuery UI.

    Where you display the records add:

    echo ‘<div id=”deletelink” title=”Confirm File Deletion”>Are you sure you want to permanently delete this record?</div>';

    Then you will need to modify the jquery JS file the new fille will look something like follows:

    $(function() {
    
    var parent = '';
    
    $('a.delete').click(function(e) {
        e.preventDefault();
        parent = $(this).parent();
    
        $('#deletelink').dialog('open');
        return false;
    });
    
    $('#deletelink').dialog({
        autoOpen: false,
        width: 300,
        buttons: {
            "Ok": function() {
                $.ajax({
                    type: 'post',
                    url: 'jquery-record-delete.php',
                    data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
                    beforeSend: function() {
                        parent.animate({'backgroundColor':'#fb6c6c'},300);
                    },
                    success: function() {
                        parent.slideUp(300,function() {
                            parent.remove();
                        });
    
                    }
                });
                $(this).dialog("close");
            }, 
            "Cancel": function() { 
                $(this).dialog("close"); 
            } 
        }
    });  
    
    
    });
    

    The key here is declaring your parent var holder at the top level and then moving the ajax call to the dialog.

    Enjoy!

  35. Kyle

    This is great! Works like a champ. How would I be able to achieve the same effect, except when I add a new record?

  36. Yugan

    hey im an absolute beginner, somehow the above example didnt work for me. but i googled and made mine working with the following example:

    Link >> http://www.phpsimple.net/mysql_delete_record.html

    now how do you do it with ajax request using jquery.

    thanks a lot guys!!!

  37. Florian

    Thanks for this cool example incl. dialog confirm :)

  38. Ken

    Thanks for the fantastic deletion script!

    How would one go about doing the opposite of this and have a text field to ADD records to the db and animate the insertion of the new item in the list at the appropriate spot (either alphabetically or numerically)?

  39. Ken

    …with jQuery…I forgot to mention :)

  40. I just cant get this to work, i followed the instructions on how to get it to work with a table but it goes 2 ways: 1. Deletes the record without animation. 2. Shows a weird animation (seems like the parent td’s get removed, and then it slides up) but this doesnt delete it from the database.

    I got the a.delete class right, but where to put the id mentioned earlier, and what do i use for a name for that id.

    Thanks in advance..

  41. Well, i saw the light hehe and got it to work, it animates and deletes the record from the db. The only thing it still doesnt do correctly is show the fade to red and slide up nicely (in a table). It still seems like the parent td gets removed so the text and delete button moves to the left and then slides up. Anyway to fix this ?

  42. @Maik:
    Are you importing the jQuery plugin ‘Color‘?
    This was my issue for a bit.

  43. No, i did not actually, thanks this works fine now !

  44. Me again ^^

    I’m trying to implement the confirmation box, but i cant get it to work.

    I keep getting the error: $(“#deletelink”).dialog is not a function

    Plz help me out !

  45. note to self
    Implement Jquery UI library before complaining :P

  46. anon

    sql injection, please don’t post tutorials that contain massive security flaws like that

  47. @Anon: This would be behind a password protected area. Moreover, I typecast the $_GET[] var so there’s no injection. You’re wrong.

  48. Martijn

    Hi David!
    Is it also possible to use this outside wordpress?
    I’ve tried using this on a project i’m working on but it drives me crazy that it won’t work..
    I never worked with AJAX though, but i guess it’s not that difficult as PHP?

    Thnx in advance!

  49. @Martijn: Yep, you can use this for anything — don’t need WordPress at all.

  50. Martijn

    @David: Okay, but why is it that nothing happens? I really copied the exact source code into a DIV element of mine.. But the frikkin page doesn’t do crap..

  51. Martijn: How can me or anyone else help if you don’t provide any sample code?

  52. Oceanborn

    Dear David, thank you for your script! I’ve installed it and this effect works, but is not working php script that deletes comments. It all the time deletes the last comment, regardless of the click to remove. Maybe it is because I use the files, not the database? Help me please. Thank you. (Sorry my bad English)

  53. Oceanborn

    Never mind, I have done this problem. But now I have another problem: when I delete a comment, I change the following comments in less than 1 room, and id div remains the same and when I remove coment, it removes the following comment. Give me please how to change id div following comments?

  54. Oceanborn

    Thanks, I have done and this problem. Thanks you for your amazing script!

  55. BMiller (or anyone with an answer), What do you mean by:
    var parent = ”;
    that’s not working… I am assuming you wanting to say var parent = ‘(something in here)'; ? either way, please clarify.. I am using tables and managed to get to the parent tr by doing$(this)parent().parent()but in trying to use the modal box it all breaks, animation and everything works as intended except for the db deletion.yes I made sure everything works without the modal box. I am pretty sure (tell me otherwise if it’s otherwise!) it’s the parent var holder that I am having issues with… how do I define this exactly?your help is much appreciated thank you!

  56. ziad

    can we do it using xml files not database? how? anyhelp:D thanks

  57. Hi,

    I have just started to learn jQuery. And for my admin panel i did implemented this cool effect. This is really very nice. Now i have another type of question. My question is like…

    when i click on delete it just deletes but in some cases i have t check that weather this id is associated with some other table and if it is with some important table than it wont get deleted. so is it possible to do this ? and if it than how ? record must not be deleted when it is associated with other table.

    Do let me know.
    Thank you.

  58. Unni

    Can i use this functionality inside an iframe?

    I need to show some data in a scrollable iframe and remove each row (which has an delete image) by clicking the delete image.

    Is this possible?

  59. jayz

    hey, i have tried your trick tips.

    Unfotunately when i click the ‘delete’ button it just candy my eyes that the row is deleted but not in the database.

    I just follow your code just clear. Could you give me some idea?

  60. Very nice article. Not getting the color animation to work confused me for a while until I found the color plugin :)

    As a few people have mentioned security. Type casting is good practice but I’ve always understood that you should use it along with a claned inout – not relying solely on the typecast. E.g. you could have easily changed the query to:

    $id = .(int)$_GET['delete'];

    $query = sprintf( “DELETE FROM my_table WHERE item_id = ‘%s'”, mysql_real_escape_string($id) );

  61. Mike

    This is very cool, however, I am having the same difficulty that Maik Diepenbroek is having. My results are displayed in a table, so the animation/delete is working, however, the effect is very jagged causing the data to kind of shift to the left and it is not as smooth as the effect you have featured here. Any ideas as to what may be causing this? Here is my sample code:

    print("    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        $bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');   
    
        echo '<tr bgcolor="'.$bg.'" class="record" id="record-'.$row['user_id'].'">
        <td align="left">'.$row['username'].'</td>
        <td align="left">'.$row['first_name'].'</td>
        <td align="left">'.$row['last_name'].'</td>
        <td align="left">'.$row['rd'].'</td>
        <td align="left"><a href="edit_user.php?id='.$row['user_id'].'">Edit</a></td>
        <td align="left"><a href="view_users.php?delete='.$row['user_id'].'" class="delete">Delete</a></td>
        </tr>';
    }
    echo '</table>';");
    
  62. Mike

    This is very cool, however, I am having the same difficulty that Maik Diepenbroek is having. My results are displayed in a table, so the animation/delete is working, however, the effect is very jagged causing the data to kind of shift to the left and it is not as smooth as the effect you have featured here. Any ideas as to what may be causing this? Here is my sample code:

    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        $bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');   
    
        echo '<tr bgcolor="'.$bg.'" class="record" id="record-'.$row['user_id'].'">
        <td align="left">'.$row['username'].'</td>
        <td align="left">'.$row['first_name'].'</td>
        <td align="left">'.$row['last_name'].'</td>
        <td align="left">'.$row['rd'].'</td>
        <td align="left"><a href="edit_user.php?id='.$row['user_id'].'">Edit</a></td>
        <td align="left"><a href="view_users.php?delete='.$row['user_id'].'" class="delete">Delete</a></td>
        </tr>';
    }
    echo '</table>';
    
  63. I realise it is a demo… but should it not be a post request to delete things rather than a get? You know… to promote good practices.

  64. Oh ya… someone duplicated the content… http://www.ajaxupdates.com/animated-ajax-delete-jquery/

  65. AM

    Any idea what I am doing wrong. The function looks like this

    $(document).ready(function() {
    	$("a.delete").click(function(e) {
    		e.preventDefault();
    		var parent = $(this).parent("td").parent("tr");
    		$.ajax({
    			type: 'get',
    			url: 'manage_documents2.php',
    			data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
    			beforeSend: function() {
    				parent.animate({'backgroundColor':'#fb6c6c'},300);
    			},
    			success: function() {
    				parent.slideUp(300,function() {
    					parent.remove();
    				});
    			}
    		});
    	});
    });
    

    and the PHP/HTML like this

    <tr id='record-'>.<a href="?delete=" class="delete">

    However nothing happens when I click on my delete icon

  66. divyesh

    Hi,
    u did great job but still there is something remains. i think u need to put a confirmation message for delete.

  67. John

    @Mike: Can you move a table row up? Nope, so don’t simply fade it away!

    So
    parent.slideUp(300,function() {

    Becomes
    parent.fadeOut(‘slow’, function() {

    There are other effects but this is seemingly the most practical for this application.

  68. Hi Walsh,

    I used this for my project.
    Its cool man !
    Thanks for your post
    Regards
    Sushant Danekar

  69. Jay

    @Kyle:

    Hi Kyle, I am having the same problem.. am able to get it working but struck with removing newly added records.

    Have you found any solution? Really appreciate if you can drop a note.

    I also checked the David’s note below but it is mootools I need to totally move it.

    @Kyle:

  70. Ikramy

    Thanks for the post.

    The script doesn’t work on Google Chrome. Also, the script doesn’t work as expected when you have nested DIVs or SPANs inside the record DIV.

    • sjg

      On Chrome it is hanging up on the beforesend. I removed the beforeSend and just added the background color styling when the delete button was clicked. Tested and works in IE, Mozilla and Chrome.

  71. Hey Guys I have tried to implement this into a projetc im working on. I simply want to delete records from a database. The only change I have is to change $_GET to $_POST.

    I am recieving $link as an undefined variable. I cant see anywhere in the tut of where it is declared.

    Does the value of the record in the database need to be an integer?

    The other two errors I am receiving are very similar. They are:

    mysql_query() expects parameter 2 to be resource, null given in C: (line 32)
    

    AND

    mysql_fetch_assoc() expects parameter 1 to be resource, null given in C: (line 33)
    

    these lines in the tut are:

    $result = mysql_query($query,$link);
    while($row = mysql_fetch_assoc($result))
    

    hope someone can help. thanks.

    Reece Cropley

  72. @Martijn:

    The OP has clearly explained that the example doesn’t actually delete records – that not the point of this tutorial (you’ll need a sql tutorial if you want to actually delete a record).

    Also, how could anyone possibily help you without any source code? It amazes me that people still post such vagues requests.

  73. @Reece Cropley: If you’re deleting a single record why are you using a loop? I think you need to go and read a beginners tutorial on php with mysql – w3schools.com have a few good ones – the examples will make a lotmore sense then).

    FYI you’code would be along the lines of:

    $delete_sql = “DELETE FROM users WHERE userid=$id”;
    $res = mysql_query($delete_sql);

  74. EDIT: ah see what you mean with the link variable. As this is a web dev related site the Op has assumed you know the very basics of connecting to a MySQL database – which is what the link var is being used to do.

    You REALLY need to go an read some basic tutorials ;)

  75. I gave the script a try. And since I’m using table, I don’t use the sample code (instead, I use the one mentioned by John). And it works, the “tr” fade and then the row is removed from table (shifting the row below upwards).

    BUT the thing is, the record isn’t really deleted.
    When I refresh the page, the previously deleted row, get shown again. I checked the database, just to found the record is still there.

    So I checked my MySQL command, and it works just fine.

    $query = "DELETE FROM mytable WHERE id = ". $_GET['delete']."";

    When I copy the “delete” link and run it directly through the address bar, the record is deleted permanently.

    So can anyone give me a hint, where should I look?

  76. sorry about the rapid-replies, got some lag..

    and I’ve found the solution, thanks to Francesco

    Don’t forget to add the id to tr.

    • Augusto C SAntos

      nicive, i´m having the same problem. What is the solution ? Thanks

    • I add the ‘id’ in the tag:

      that simply solve my problem.

  77. Nice articles… could you please add some indentation to your another code samples? Thanks!

  78. Biblop

    Nice and very simple but useful tip.
    Thanks a lot and please continue to make us improve ourself :3

  79. Ajay

    nice code.
    but i have a little problem.
    when im using this the page still refreshes.
    the deletion works fine except the refresh part
    can you help

    include('pagina.js');
    include('connect_db.php');
    
    if(isset($_GET['delete']))
    {
    	$query = 'DELETE FROM RequestLines WHERE RequestLineId = '.(int)$_GET['delete'];
    	$result = mysql_query($query);
    }
    print "hallo welke wil je verwijderen"; //text
    
    $query = 'SELECT * FROM RequestLines where RequestId =670 ';
    $result = mysql_query($query);
    while($row = mysql_fetch_assoc($result))
    {
    	echo '
    				verwijder
    				',$row['RequestLineId'],'
    			';
    }
    
  80. milo

    impressive delete
    it has some problem when used inside jquery tab with paging involved

  81. butch

    sorry for the previous post… I’m a newbie to jQuery, and your demos here are quite exceptional. I’m trying to integrate this functionality on my app, and it turned out good, except for the part that the deletion is done for a particular table… anyway, my problem is this, i displayed various rows from two tables, and when a user deletes a row, the Jquery works, but my problem is that i couldn’t reflect the deletion on the database because i couldn’t determine from the two tables, which table should i delete…

    specifically,

    if( isset($_GET['delete']) ){
           if(isset($_GET['table']))
    		$sql='DELETE FROM table1 WHERE id='.(int)$_GET['delete'];		
    	else
                    $sql='DELETE FROM table2 WHERE id='.(int)$_GET['delete'];		
    }
    

    i noticed, i couldn’t add a variable on the parameter, because it is done through the javascript… i tried checking if the ‘ajax’ variable is set in the $_GET method, and it is.. how could i add another variable in the $_GET method through javascript? i hope my question is correct?

    thanks!

  82. butch

    problem solved.. i created another class and have that passed to the jquery function :)

  83. saeed

    this script not working for me, i have tried something like that

    $(document).ready(function() {
    	$('a.delete').click(function(e) {
    		e.preventDefault();
    		var parent = $(this).parent();
    		$.ajax({
    			type: 'get',
    			url: 'jquery-record-delete.php',
    			data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
    			beforeSend: function() {
    				parent.animate({'backgroundColor':'#fb6c6c'},300);
    			},
    			success: function() {
    				parent.slideUp(300,function() {
    					parent.remove();
    				});
    			}
    		});
    	});
    });
    
    while($row=mysql_fetch_array($result)){
    	echo '
    	
    		' .$row['product_id']. '' .$row['title']. ''. $row['price']. '
    	
    	';
    }
    

    and the delete part another page called delete.php

  84. yazer

    It would be easier to have a “zip” file for full source code
    I managed to make it work, but the CSS is messed up! it doesn’t look as it should be :S

  85. Geoff

    Great script, thanks. All seems to be working, but if I return a “$return = false” from my delete script the success function still proceeds. (I am guessing that the ‘success’ is indicating the script was processed). How do I read the return value?

    Thanks
    Geoff

  86. @Geoff: You need to change the script slightly:

    php:

    if(isset($_GET['delete']))
    {
    	$query = 'DELETE FROM my_table WHERE item_id = '.(int)$_GET['delete'];
    	$result = mysql_query($query,$link);
    	echo (int)$result;
    	die();
    }
    

    js: change the success part of the code

    success: function(data) {
    	if(data == 1){
    		parent.slideUp(300,function() {
    			parent.remove();
    		});
    	} else {
    		alert('oh no something went wrong!!!');
    	}
    }
    
  87. Geoff

    @SeanJA: THANKS!! More than you know! It’s now 12:42am… now I can sleep tonight (i.e., .after Italy Vs New Zealand ;-) )

    Cheers!
    Geoff

  88. Kamal

    Very nice one, thank you all.

    Let see this like a shopping cart :

    1) This tutorial has implemented Delete from cart (from database table A).

    2) How to implement with jquery the Add to cart (to database table A) from table B. ??

    what the good design to do it :
    – with a popup window showing recods from table B.
    or
    -jquery accordion showing table B recods.

    Thanks, your help is appreciated.

    Kamal

  89. J

    would their be a way to use this script but instead of delete have it used to add an entry to a mysql table? so a user enters a name into a name and email into a form and then without page refresh their name and email is added the a below listing of names and emails

  90. Mattias

    Sorry for the spam, but i just really wanna post my code.

    All these posts was caused due too – sorry!

    $(document).ready(function() {
    	$('a.deletePage').click(function(e) {
    		var answer = confirm("Ønsker du at slette denne side?");
       if (answer){
    		e.preventDefault();
    		var parent = $(this).parent("td").parent("tr");
    		$.ajax({
    			type: 'get',
    			url: 'pages.php',
    			data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
    			beforeSend: function() {
    				parent.animate({'background-color':'#fb6c6c'},300);
    			},
    			success: function() {
    				parent.fadeOut(300,function() {
    					parent.remove();
    				});
    			}
    		});
    	}
    	});
    });
    
  91. Jason

    Mattias,
    instead of:
    if (answer){…

    try:
    if (answer == true){
    //code if they click ok
    }else{
    //code if they click cancel
    }

  92. Jason

    j,
    to add to a table you could do the following after the ajax returns the results. The results would have to have the stuff.

    $('.tableClass').find('thead').append(results);  //this will add the result to the top of the table under the head
    

    If you are not using a table you could simply do the following

    $('.DivWrapperClass').append(results);
    

    where results would be another div added to the end of the of the list

  93. Mattias Fjellvang

    Thanks Jason – working perfectly now.

    Another question, and according to J’s question and your answer.

    I don’t quite understand – how could you add it into a database, and in a table, containing the information.

    How would you add it into this code, pretending it was and ADD instead of delete.

    $(document).ready(function() {
    	$('a.deleteIp').click(function(e) {
    		var answer = confirm("Do you wish to delete this data?");
       if (answer == true){
    		e.preventDefault();
    		var parent = $(this).parent("td").parent("tr");
    		$.ajax({
    			type: 'get',
    			url: 'ipsettings.php',
    			data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
    			beforeSend: function() {
    				parent.animate({'background-color':'#fb6c6c'},300);
    			},
    			success: function() {
    				parent.fadeOut(300,function() {
    					parent.remove();
    				});
    			}
    		});
    	}
    	});
    });
    
  94. Mattias Fjellvang

    And by the way, with the above code, my dosen’t change to red when it fades out?

    $(document).ready(function() {
    	$('a.deleteIp').click(function(e) {
    	var answer = confirm("Do you wish to delete this data?");
    	if (answer == true){
    	e.preventDefault();
    	var parent = $(this).parent("td").parent("tr");
    	$.ajax({
    		type: 'get',
    		url: 'ipsettings.php',
    		data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
    		beforeSend: function() {
    			parent.animate({'background-color':'#fb6c6c'},300);
    		},
    		success: function() {
    			parent.fadeOut(300,function() {
    			parent.remove();
    		});
    		}
    		});
    	}
    	});
    });
    
  95. Mattias Fjellvang

    my table TR* dosen’t fade out in red. It just fades out.

  96. For those who have the problem ‘It doesn’t turn red’ above

    You need to have the jquery color plugin called in your header. Dont just copy and paste… look at the source code of the document

    Plugin is here.
    http://plugins.jquery.com/project/color

    Nice Tutorial David.

    • No you don’t, you might be having the problem because IE doesn’t render fades well, or it could also be because that code is not being called at all.

    • It depends on the jquery package you have installed,

      The plugin was neccessary when I tested it, woulodn’t work without. for info this was FF, who uses IE these days :)

  97. Also, after reading a few other posts,

    For those who want the ‘Are you sure message’ to appear on click, you can actually pulll in a standard javascript call:

    onclick=”return confirm(\’Are your sure you want to Delete this Item?\’)”>

    Add it to the href and hey presto.

    • No you don’t need to do it that way, just add it to the onclick functionality:

      $('a.deleteIp').click(function(e) {
          e.preventDefault();
          if(confirm('are you sure?')){
              //do the delete stuff
          }
      });
      
    • Agreed, though the traditional Javascript will also work.

      I like you solution but tend to use something along the lines of:

      $(‘a.deleteIp’).click(function(e) {
      var answer = confirm(“Do you wish to delete this data?”);
      if (answer == false){
      return false;
      }
      if (answer == true) {
      }
      }

      This becomes useful when you wish to provide an alternate action when the result is false.

  98. duy

    i don’t understart : data: ‘ajax=1&delete=’ + parent.attr(‘id’).replace(‘record-‘,”),

    .atr(‘id’) :S

  99. This script helped me solve a problem back a year or so ago, and was the foundation that i used to later create far more advanced AJAX UI driven apps. was just going through my bookmarks and found this page again heh :)

  100. I just want to say thanks for this interesting thread about Animated AJAX Record Deletion Using jQuery! Regards, Alexa Beratung

  101. sants

    I have a big problem that is making me crazy.
    I need to delete the record using two WHERE params, so my query is like this:

    DELETE FROM my_table WHERE item_id = '.(int)$_GET['delete'].' AND my_field = '.$_GET['id']

    Unfortunately this code doesn’t work.

    My $_GET['id'] return a number like ‘8’ and work correctly, cause if I print $_GET['id'] it show the number I expect to see.

    Probably I have to get this number from another variable, any suggestion?

    • sants

      problem solved, thanks anyway

  102. Aran

    Your code has been copied and re-used as someones own on a different website…

    http://www.9lessons.info/2010/11/delete-records-with-color-change-effect.html

    He even posted a comment on this post…

  103. Daniel

    what to do to be able to delete the record by clicking the button, not a href? Please help.

  104. sansak

    How to really delete data from MySql.

  105. Mathew King

    The color animation won’t work by this code:

          beforeSend: function() {
            parent.css('background-color', '#ff0000');
          },
    

    Is there something specifically i have to do?

  106. I add the ‘id’ in the tag:

    that simply solve my problem.

  107. this is how I did it

  108. Nomi

    @David thanks for this wonderful code .. i need a little help . i got this code working only javascript part is not working as change color and fade style .. can you please guide me

  109. Shane

    Ive been trying to get the database delete working for two days now but no success.

    Everything else works but it seems that $_GET['delete'] is never set even after the delete link is clicked so no matter what i put inside the isset conditional, even a simple echo statement, its never run?

    • Sven

      I had the same problem. Try removing ajax=1& from the data part. Worked for me.

  110. Bonz

    Can’t save also to database.

  111. aisha

    hellooo , i m new in ajax..

    i had try the coding but its not working in jQuery.. why?

  112. [...] web sitelerinde gördüğünüz efekt vererek silme işlemini 19 satırlık jQuery kodu ile burada olduğu gibi kolayca [...]

  113. Java West

    Thanks alot it worked nice and all I would like to ask is it possible u include a confirmation message ?

  114. Joshua

    Hi, this is an awesome script but since I am a js/jQuery n00b it isn’t working for me. :P I don’t know what I am missing, but for some reason when I click my delete button it just reloads the page (the script is at the top of the page) and deletes it, but not asynchronously.

    Link: ($removelink)

    Delete
    

    Element I Want to Delete:

    <div id="post-" class="chatmsg">
    <a href="/user/" >
    

    jQuery

    $(document).ready(function() {
      $('a.delete').click(function(e) {
      	e.preventDefault();
    	var parent = $(this).parent();
    	  $.ajax({
    		type: 'get',
    		url: 'index.php',
    		data: 'ajax=1&delete=' + parent.attr('id').replace('post-',''),
    		beforeSend: function() {
    		  parent.animate({'backgroundColor':'#fb6c6c'},300);
    		},
    		success: function() {
    		  parent.slideUp(300,function() {
    		  parent.remove();
    		  });
    		}
    	  });
      });
    });
    

    Like I said, I just know the basics of jQuery at the moment and am still learning. If anyone can help me understand why it’s redirecting rather than doing it asynchronously (I thought preventDefault() stopped that) that would be great.

  115. Awesome effect!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!