Home > Tutorials > Javascript > jQuery > Delete Row Animation WordPress Style In jQuery + Adding MySQL Delete
Permalink to Delete Row Animation WordPress Style In jQuery + Adding MySQL Delete

Delete Row Animation WordPress Style In jQuery + Adding MySQL Delete

by on 02.19.2009 | 18 comments

Ok, so yesterday I did a tutorial about making a animation similar to that which WordPress uses when you delete posts etc. You know the [...]

Ok, so yesterday I did a tutorial about making a animation similar to that which WordPress uses when you delete posts etc. You know the fade to red & slide up thing… Yep? Good.

Well I didn’t include how to add the ajax so that it could actually delete since I thought it would be fairly easy for everyone to do themselves… Boy, I was wrong. For the novice jQuery coder it actually turns out to be a little bit difficult. So starting off from the end of the last post, here is how to add ajax so that you can actually delete stuff.

A little note: I make use of the mysqli class which is built into PHP, you can use mysql, but I’m not going to cover that since if I find mysqli to be a lot better and neater.

Let’s Get To It

When we last saw the javascript it looked like this:

$(function(){
	$('.box a').click(function() {
		$(this).parents('div.box').animate( { backgroundColor: '#cb5555' }, 500).animate( { height: 0, paddingTop: 0, paddingBottom: 0 }, 500, function() {
			$(this).css( { 'display' : 'none' } );
		});
	});
});

That Funky PHP Code – Listing

Well that just won’t do it, but first we need to swap out our hard coded HTML for some funky PHP script. Remember you need a database and some data to show, I can’t help you out with that though. Here is the code I use to show some rows:

<?php
//Right at the top of the page. Yes, even above the DOCTYPE
$mysql = new mysqli('localhost', 'root', '', 'wp-delete-ani');
?>
<?php
//In where the content will go.
$result = $mysql->query('SELECT * FROM `wp-delete-ani`', MYSQLI_STORE_RESULT);
while(list($id, $text) = $result->fetch_row()) {
	echo '<div class="box" id="delete-'.$id.'"><a href="#">delete</a><strong>'.$text.'</strong></div>';
}
?>

Right that should do it. Of course you need to change the login data and query to suit your database, but again only you can work that one out. Also if you need to change the HTML output you’ll have to do that too. The code is pretty basic, but I’ll go over it quickly. We query the database, I use list to store the info into pre-named variables. You could however use the classic $row = $result->fetch_row(); method to get $row as an array with all your data in it.

There is one thing about the HTML that is very, very important. For the code to work correctly jQuery needs some way of getting the id from the database so it can tell PHP which row to delete. That is what the id="delete-'.$id.'" bit is for. More on what jQuery does with that a little later.

That Funky PHP Code – Deletion

Ok, now we need to write the PHP that acts on deletion. I have attached it to the top of my display page, but it’s probably best put on another page. Here’s what I have:

//Remember me above the DOCTYPE...
$mysql = new mysqli('localhost', 'root', '', 'wp-delete-ani');
//This is the new deletion stuff...
if(isset($_POST['ajax'])) {
	if(isset($_POST['id'])) {
		$id = (int)$_POST['id'];
		if($mysql->query("DELETE FROM `wp-delete-ani` WHERE id = ".$id)) {
			echo 'excellent';
			exit(0);
		}
	}
}

This is also pretty simple. We’ll be making the jQuery post an ajax variable & the id to delete so that we know to act on ajax and not load the page content. We check for that variable, if it’s there then we look for an id in the POST array. As secure as POST generally is, it sometimes isn’t secure enough so we store id in a variable $id and typecase it using (int) that means it will always end up as an integer. There’s probably a better way to do that, such as using is_numeric() to check if it is a string number first, but this will do for this example. We finally run the query, which again will have to be customised but the basic structure is the same, in an if to see if it returns true or not. You could have it do something on failure if you like. If it works we echo something so we can see the output in Firebug for debugging and exit to stop PHP in it’s tracks so we don’t get all the HTML in our AJAX request.

Changing The jQuery

So we need to change the jQuery a little. Let’s see what it looks like after the changes:

$(function(){
	$('.box a').click(function() {
		id = $(this).parents('div.box').attr('id');
		id = id.replace(/delete-/, "");
		el = $(this);
		$.post('jquery-wp-delete.php', { id: id, ajax: 'true' }, function() {
			$(el).parents('div.box')
			.animate( { backgroundColor: '#cb5555' }, 500)
			.animate( { height: 0, paddingTop: 0, paddingBottom: 0 }, 500, function() {
				$(this).css( { 'display' : 'none' } );
			});
		});
	});
});

Different huh? Ok, let’s go through it a bit. We have the click function again. Next, because we need an id to give to PHP, we grab the id attibute of the div that is the parent of the link we clicked. I hope that makes sense. We then use javascript’s replace to find delete- from the id which looked like delete-4 so we end up with just the number. Next we assign the scope of this to a variable for use later.

Then we make the AJAX call via POST. I’ve called back to the same page, but I’d advise putting the delete code on a seperate file. We give data in the form of the id we got before, plus we send a variable ajax with the value true so we can tell it was from an AJAX call. Then we put the animation from before into the callback of the AJAX call which is only ran if the AJAX call didn’t fail. The animation is the same except for the start which instead of saying $(this) we change it to $(el) since $(this) does not have the same scope as it did before.

Hopefully that all makes sense. I can’t give an example of the MySQL part working, but here is a link to the example of the animation from before.

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Discussion: 18 Comments

  1. Jun 23rd, 2009 @ 15:15:09

    This is good. I already have a wordpress comment thing that removes commments etc, but it doesn’t actually do anything yet other than the animation so this is really usful as I will integrate this with mine.


  2. Jun 23rd, 2009 @ 15:21:34

    Thanks. :) Glad you found a use for it.


  3. Dec 22nd, 2009 @ 19:12:37

    Hey. I couldn’t get through to this page the other day. Anyone else had the problem?


    • Dec 22nd, 2009 @ 19:14:26

      If you mean you could not get the site to load it could have been because we’ve been getting attacked by hackers a lot recently. Everything should be ok now though. ;)


  4. Feb 5th, 2010 @ 15:14:32

    Tally-ho!

    Again, I’m trying to do this for the front-end of things. Everything is dandy except for the ever-dreaded Responce 0 :/

    add_action('wp_ajax_playlist_data_delete', 'playlist_delete');
    
    function playlist_delete() {
    	global $wpdb;
    	$wpdb->show_errors();
    	$table_name = $wpdb->prefix . "playlist_master";
    	$id = $_POST['id'];
    
    	if(isset($_POST['ajax'])) {
    		if(isset($_POST['id'])) {
    			if($mysql->query("DELETE FROM $table_name WHERE id = ".$id)) {
    				echo 'excellent';
    				exit(1);
    			}
    		}
    	}
    die(69);
    }

    Note that

    $wpdb->show_errors();

    doesn’t throw me a bone. I simply get response 0.

    Any thoughts?


  5. Feb 5th, 2010 @ 15:19:54

    btw, my POST looks fine:

    ajax true
    id 39


  6. Feb 5th, 2010 @ 16:05:05

    Ok. Not sure where that 0 is coming from as there is nothing in your code that seems to be able to produce that.

    Again though as this is function receiving data via AJAX I would add in a nonce & verify it via check_ajax_referer() before even attempting to delete a row so external requests can’t trigger a deletion.

    I’ve never made a AJAX call to admin-ajax.php without providing a nonce so maybe it is refusing your AJAX request (returning 0) because no nonce is being verified. Although I’m not sure about that.

    Also just another little thing I noticed, you have wrote:

    $id = $_POST['id'];
    //later in code
      if(isset($_POST['id'])) {
    

    That is slightly backwards, you should probably use:

    if(isset($_POST['id'])) {
      $id = (int) $_POST['id'];
    

    Hope that makes sense. ;)

    I’ll check a few more things out about why your code could be giving back 0, but let me know if you find anything else in the meantime. :)


  7. Feb 5th, 2010 @ 16:44:31

    nonce… that’s a whole new can of worms opened for links.

    I’ve been staring at this all day, I’m sure it’s the solution. Now, I’m just too bug eyed to figure thinks out. Methinks it’s time for a brewski.


  8. Feb 5th, 2010 @ 17:16:22

    Well it’s pretty much the same as your insert function. Send the nonce with your form using wp_create_nonce(); and then verify it in your delete function using check_ajax_referer();.

    I think a `brewski` is indeed in order. ;) If you noticed the site was down about 5-10 minutes ago I apologise, someone overloaded the server & I had to get onto the admins to get it sorted. All done now though. :D


  9. Feb 8th, 2010 @ 11:53:22

    I have to build a form instead, I can’t get my head around wp_nonce_url makes no sense to my pea sized brain :)


  10. Feb 8th, 2010 @ 12:25:16

    Ahhh ok if you don’t have a form, it is a little different, but not by much. I’m going to assume you are using a click event to make a text link trigger the delete command via AJAX.

    To send across the extra data, in this case the nonce you could do this:

    jQuery.('#delete-link').click(function() {
    	jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', { id: '<?php echo $id; ?>', wpsec: <?php wp_create_nonce('your-action-text'); ?>' }, function(response) {
    		//callback function here
    	});
    	return false;
    });
    

    Something like that should do the trick. The return false is just there to stop the href from submitting (if you used an href).

    Hope that helps & let me know how it goes. ;)


  11. Feb 8th, 2010 @ 13:09:41

    AAAH, yes. Obviously, just add what needs to be sent where it’s being sent from! Thanks for getting in the fray :)

    Now, only one slight thing,

     id: id, wpsec: '<?php wp_create_nonce('something'); ?>' }

    doesn’t return anything in wpsec:, so I made a function instead and echoed that, which works.

    But I still get response 0 :/

    As you, I can’t see where we should get 0. Here’s the code:

    add_action ('wp_footer', 'delete_mpl_jquery');
    function delete_mpl_jquery() { 
    
    $noncense = wp_create_nonce('something'); ?>
    
    <script type="text/javascript">
    jQuery(document).ready(function($){
    	$('.box a').click(function() {
    	id = $(this).parents('div.box').attr('id');
    		id = id.replace(/delete-mpl-/, "");
    		el = $(this);
    	jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', { id: id, wpsec: '<?php echo $noncense; ?>', ajax: 'true' }, function(response) {
    		//callback function here
    	});
    	return false;
    });
    });
    
    </script>
    <?php } ?>
    
    <?php //this is the SQL and php for deleting playlists
    
    add_action('wp_ajax_playlist_data_delete', 'playlist_delete');
    
    function playlist_delete() {
    	global $wpdb;
    	$wpdb->show_errors();
    
    	$piktud =  $_POST['id'];
    
    	check_ajax_referer('something', 'wpsec');
    
    	$table_name = $wpdb->prefix . "playlist_master";
    
    	if(isset($_POST['ajax'])) {
    		if(isset($_POST['id'])) {
      			$id = (int) $_POST['id'];
    			if($wpdb->query("DELETE FROM $table_name WHERE id = ".$id)) {
    				echo 'excellent';
    				exit(1);
    			}
    		}
    	}
    die(69);
    } ?>

  12. Feb 8th, 2010 @ 13:19:51

    I’ve also tried

    check_ajax_referer(‘something’);
    check_ajax_referer(‘something’, ‘wpsec’);
    check_ajax_referer(‘wpsec’, ‘something’);
    check_ajax_referer(‘wpsec’);

    all response 0 :(


  13. Feb 8th, 2010 @ 14:15:42

    Forgot to mention that without sending an action in the $_POST array WP won’t have a clue what PHP function to call, exactly the same as you form on your insert code.

    So in this case you need to add an extra post value to your jQuery ajax call. The key would be action and the value playlist_data_delete.


  14. Feb 8th, 2010 @ 14:34:41

    Thank you so much, that did it! I’ll make sure to send you another donation, imacs are cool and so are you.


  15. Feb 8th, 2010 @ 14:55:50

    No problem, glad to help and Thank you. :)


  16. Sep 1st, 2011 @ 07:58:39

    please Demo and download link


    • Sep 1st, 2011 @ 13:49:18

      The demo link is at the bottom of the post, and I can’t give a download link as the code needs to be integrated into your own application/code.


Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required