How to delete row in html table using ajax


In this tutorial we are going to see the complete example to delete entire row from the HTML table using AJAX and jQuery. We are using AJAX call request to call the php function to delete the record from mySQL database table as well.

Why are we using AJAX to delete the row from the HTML Table?

AJAX helps in managing action on HTML elements without any page refresh.


First lets look into the following steps before proceeding with the code.

  • Assigning the class "tblrow" to each row in HTML table.
  • Adding a delete button to each row by assigning the class "remove" and attribute id with mysql fetched user ids.
  • Write a php function "deleteUser" to delete record from mySQL "wd_users" table.
  • Write a jquery function to trigger a click event on remove button.
  • Set up an AJAX call passing the userID in URL paramters to the php function.

List of file structure we use to keep things neat.

  • index.php - Includes HTML Table for list of Users.
  • users.php - Includes the deleteUser PHP function.
  • custom.js - Includes jQuery event and Ajax request function.
  • custom.css - Includes CSS classes for HTML table.

How this will work?

Clicking the delete row button will check for the closest parent tr with reference class "tblrow" and will remove the row from the table visually but this won't be enough as after refreshing the page the deleted row may reappear, So we need a AJAX call request to delete the record from MySQL users table so on next page refresh the deleted user row will not show.

Syntax

1) Code in index.php file.

Note : It is important to include the jquery library and the custom.js file path in header of index file.


	
	
	


NameAddressPhoneEmailRemove
KevinAddress One +11111111111 email1@email.com
MarkAddress Two +2222222222 email2@email.com
HectorAddress Three +3333333333 email3@email.com

2) Code in users.php file.

Here we are using the switch case as xAction for entering into case "deleteUser" executing the deleteUser function.

<?php

function deleteUser($userID){
$str = "ERR";
if($userID){
	 $query = "SELECT * FROM wd_users WHERE userID='".intval($userID)."'";
	 $results = mysql_query($query);
	  if (mysql_numrows($results)) {
			DELETE FROM `wd_users` WHERE `userID` = intval($userID);
			$str = "OK"
	  } 
	}
 return $str;
}

if($_REQUEST["xAction"]){
    switch($_REQUEST["xAction"]){
    case "deleteUser":
    include('connect.php');
    echo deleteUser($_REQUEST["userID"]);
    break;
    }
}

?>

3) Code in custom.js file.


$(document).ready(function(){
    $(".remove").click(function(){
        userID = $(this).attr('id');
		
		 $.ajax({
                url: base_url+"/users.php?xAction=deleteUser&userID="+userID,
                cache: false,
                success:function(data){
					if(data.trim() == "OK"){
					  $(this).closest('tr.tblrow').remove();
					}
                }
            });
		
    });
});