Deleting Table Rows Using JQuery and PHP

jquery_delete_rowsIn this tutorial, I will show you how you can delete table rows from database using JQuery and PHP. The interesting thing here is that we will be able to delete the rows without reloading the page and present some cool animations while deleting those rows. You will also learn table stripping or alternate row coloring technique using JQuery.

Here is the heart of the entire logic coded with JQuery:

$(document).ready(function()
{
	$('table#delTable td a.delete').click(function()
	{
		if (confirm("Are you sure you want to delete this row?"))
		{
			var id = $(this).parent().parent().attr('id');
			var data = 'id=' + id ;
			var parent = $(this).parent().parent();

			$.ajax(
			{
				   type: "POST",
				   url: "delete_row.php",
				   data: data,
				   cache: false,

				   success: function()
				   {
					parent.fadeOut('slow', function() {$(this).remove();});
				   }
			 });
		}
	});

	// style the table with alternate colors
	// sets specified color for every odd row
	$('table#delTable tr:odd').css('background',' #FFFFFF');
});

Let’s find out what’s happening here using divide and rule methodology.

$(document).ready(function()

This is JQuery’s function which runs as soon as document becomes ready. This is similar to onload event but JQuery’s function is far more faster than that. So we want to be able to run this code when page is ready.

$('table#delTable td a.delete').click(function()

If you have worked on CSS selectors then above line should not be much of mystery to you. You can use the same syntax to target elements using JQuery. Basically it says that table with id delTable and TD inside it that has hyperlink with class delete when clicked runs the code specified within this function. So when hyperlink with class named delete within TD within table with id delTable is clicked then code specified will execute.

if (confirm("Are you sure you want to delete this row?"))

We want to be able to confirm if user really wants to delete a row.

var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();

Please keep in mind that in JQuery, the $(this) always refers to the target element which in our case is hyperlink with class delete. attr is used to get or set attributes of the tags. So the id variable refers to the parent of this hyperlink which is TD and then this TD’s parent which is TR. So here we get the id attribute of this TR. In HTML code, we will assign each row’s primary key field to these TRs to identify and delete records. The data variable makes data to be sent as part of the ajax request made using JQuery. The parent variable refers to each TR containing the target element which is hyperlink with class delete.

$.ajax(
{
	   type: "POST",
	   url: "delete_row.php",
	   data: data,
	   cache: false,

	   success: function()
	   {
		parent.fadeOut('slow', function() {$(this).remove();});
	   }
 });

The $.ajax function is used to send ajax requests. Amongst its arguments, the type refers to method of request whether it POST or GET, url refers to script which will get the ajax request data and return some response, data refers to data to be sent as part of the ajax request similar to query string form, cache controls whether cache will be on or off for the request because in IE requests are cached and success function which is also attribute of the $.ajax function runs the code inside it if the request went successful.

parent.fadeOut('slow', function() {$(this).remove();});

As explained before parent refers to the TRs in our case. fadeOut function needs two arguments; animation speed and function to execute. So what this line does is that it removes parent by fading it out and then the target link by using the remove() method. In this way entire row is gone and with the help of ajax request, the record from database is also deleted. Here we have used the fadeOut animation function of JQuery but there are more animations available.

$('table#delTable tr:odd').css('background',' #FFFFFF');

This line means that apply background style to each odd TR of the table with id delTable. Now because our code executes when page is ready, therefore our table will have alternate colors for each odd row.

So that’s all there is to it.

Wasn’t that awesome? It definitely was ! The good thing is that everything was so easy to implement.

Here is the demo.

You can download it here.

.
tweet_this
.

About these ads

43 thoughts on “Deleting Table Rows Using JQuery and PHP

  1. I noticed that once I delete a row the subsequent rows do not adjust to have alternating colors any more. Can you please show me how I can have that functionality?

    • Table rows do no adjust their colors because those are assigned to them when page is loaded. For that reason, upon deletion colors won’t adjust in this particular solution. Thanks

  2. Have implemented this script, but still having issues with the url: portion. It seems that the call is never made. I put just an alert box in my delete_row.php just to test that it gets there but the file is never called. Yet, the fade out still works. Any thoughts?

  3. Thanks! I did not know about that Firebug tool, so using it helped me see a couple issues within the php file and after fixing them, it works.

    Again thanks.

  4. Thanks for the great example. I wonder if you could explain (in the same clear detail) how to go about adding a row to the top of a table with some kind of animation. What I want to try and achieve is to have the user click an “add” button. This will bring up a modal window containing a form. After the form is completed the user submits the form only to see the data slide in as a new row at the top of the table and maybe temporarily hilighted to draw the users attention to the newly added row.

    • You might like this link for the kind of solution you want:

      http://stackoverflow.com/questions/1084408/jquery-can-do-this-popup-window-for-value

      Or I would suggest you to do something like this:

      In your popup window, add code like this on top of it:

      php:

      if (isset($_POST["your_submit_button"]))
      {
      // add info into the db

      ?>

      javascript:
      window.opener.addRecord();self.close();
      php:

      }

      The addRecord() function should be on your main file which should add the row on top of the table.

      javascript:

      function addRecord()
      {
      // mimic something like this
      $(“table#delTable tr:first”).insertBefore(“
      This comes from db using php

      “);

      // animation
      $(“table#delTable tr#php from db”).hide();
      $(“table#delTable tr#php from db”).fadeIn();
      }

      I have not tried it out, let me know if it helped you :)

    • if you want to turn red background, just replace the last line with this:

      $(‘table#delTable tr:odd’).css(‘background’,’ #FF0000′);

      Thanks

  5. Delete Records slowly

    $(function() {
    $(‘.delete’).Jooria_Delete(‘id’,’Sure you want to delete this one?’);
    });

    FIRST NAME
    LAST NAME
    EDIT
    DELETE

    <?php
    while ($record = mysql_fetch_assoc($result))
    {
    $id = $record['nhis_ID'];
    $row = "”;
    $row = $row.””.”“.DELETE.”“.””;
    $row = $row.””.”“.EDIT.”“.””;
    $row = $row.””.$record['first_name'].””.””.$record['last_name'].””;
    $row = $row.””;
    echo $row;
    }
    ?>

  6. hi,
    nice example was looking for this a long time.
    i have a question?
    what are you posting to delete_row.php?
    i’m trying to delete the row in the database but i need a var?

    any ideas ?

    • Basically, the delete_row.php file contains the code to delete specified row from database. Example:

      // database connection
      $query = “delete from table where id = ” . $_POST['id'];
      mysql_query($query) or die(‘error’);

      • This part is giving me fits. Can you please tell me what will be returned with the $_POST['id'] ? maybe then I can relate that to my delete from mysql database code. Thanks

  7. Haha! Thanks, I did it! It’s my first jQuery/AJAX thingie.

    I had to remove some parents in order to work with my current HTML structure and I needed to add one more parameter:

    var data = ‘id=’ + id + ‘&’ + ‘ip=’ + ”;

    It works like a charm! I’m going to use it in several more projects of mine. You deserve a beer for accesibility and a nice explanation.

  8. have implemented this script…but i have some issues..that when i refresh the page..data which i already deleted..it is returned back…..how can i delete data permanently from database….

    • @ritu: Make sure that the ajax requests reaches the server-side script, you have specified the correct path. You can debug that in Firebug. The server-side script should contain delete query code so that record is deleted from the database:

      // database connection
      $query = “delete from table where id = ” . $_POST['id'];
      mysql_query($query) or die(‘error’);
      echo ’1′;

  9. This Ajax table row delete thingy is exactly what I am looking for. I am downloading the code as I am typing this, will check it out and use it for my project. The animated deletion looks great!

    Cheers! :)

  10. I have a quick question – My table is in all php and I dont have a unique ID for the tr
    if ($options) {

    foreach($options as $option) if ($tmp++ $link)
    {
    echo ” ;
    echo ‘‘;
    echo ” . $displays[$i] . ”;
    echo ” . $link . ‘ ‘ . $domain . ”;
    echo ”;
    $a++;
    ;

    }

    I was wondering how to go about this. Additionally I am working with wordpress – would I still use a mysql for the the delete_row.php or what kind of code would I use

  11. if anybody is unable to download the tutorial, 1 thing is skipped in the example above provided, where you need to pass the following inside the loop of the tr, td yuo are creating like this:

    %id%
    %app%

  12. hey, just wanted to let you know that this was useful for my site. I actually did everything just like you before finding this, but used your fadeOut effect instead of what I had.

    Thanks!

  13. I don’t understand how you pass the ID of the entry you want to delete from your jquery_delete_rows to your delete_row.php

    The rows in my table each has a unique ID from the database:

    Normally I would pass it like this:
    admin.php?messagetype=$messagetype&orderby=$orderby&order=$order&messageid=$row[0]&do=delete

  14. Nice one its work in all browsers,Certain jquery delete and animate script doesnt work in IE browser,Thanks

  15. Thank you for your post. I have a question: how to pass the echo message from php back to AJAX. Say if the mysql_query in delete_row.php fails, how to display this error? thanks..

  16. Sarfaz,This is really cool! The way you explaining is very easy to understand! keep it up! May the noble triple gem bless you! (Im a buddhist)

  17. Dear Ahmed,

    This article very life saver to me.
    I have tried for along time to implementing JQUERY+AJAX on my site. But always failed.
    But your explaination very clear to me. And after one hour trial finally it works.
    Many thank’s.
    May GOD Bless your efforts. Keep your good job.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s