How to Delete Table Row with Ajax, Sweetalert2 and PHP/MySQLi

Getting Started

First, we need the jQuery library, Bootstrap for a better design to our app and Sweet Alert. I've included these files in the downloadable of this tutorial but if you want, you can download them yourself using the links below:

Creating our Database

Next, we create the database that we are going to filter in this tutorial.

I've included a SQL file in the downloadable of this tutorial. All you have to do is import the said file. If you have no idea on how to import, please visit my tutorial How import .sql file to restore MySQL database.

You should be able to create a database named mydatabase.

you can also run the code below in the SQL page in phpmyadmin

  1.         CREATE TABLE `members` (
  2.           `id` int(11) NOT NULL,
  3.           `firstname` varchar(30) NOT NULL,
  4.           `lastname` varchar(30) NOT NULL,
  5.           `address` text NOT NULL
  6.         ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  7.  
  8.         ALTER TABLE `members`
  9.         ADD PRIMARY KEY (`id`);
  10.  
  11.         INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
  12.         (1, 'neovic', 'devierte', 'silay city'),
  13.         (2, 'gemalyn', 'cepe', 'bohol'),
  14.         (3, 'julyn', 'divinagracia', 'e.b. magalona'),
  15.         (4, 'lee', 'ann', 'bacolod city'),
  16.         (5, 'tintin', 'demepanag', 'talisay city');
  17.  
  18.         ALTER TABLE `members`
  19.           MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

Creating our Table

Next, we create our table where we show the data from our database. Create a new file, name it as index.html and paste the codes below.

  1. <!DOCTYPE html>
  2.         <meta charset="utf-8">
  3.         <title>How to Delete Table Row using Sweetalert2 with PHP/MySQLi</title>
  4.         <link rel="stylesheet" type="text/css" href="asset/bootstrap/css/bootstrap.min.css">
  5.         <link rel="stylesheet" type="text/css" href="asset/sweet_alert/sweetalert2.min.css">
  6.         <style type="text/css">
  7.                 .mt20{
  8.                         margin-top:20px;
  9.                 }
  10.         </style>
  11. </head>
  12. <div class="container">
  13.         <h1 class="text-center mt20">Delete Table Row using Sweetalert2</h1>
  14.         <div class="row justify-content-center">
  15.                 <div class="col-sm-8">
  16.                         <table class="table table-bordered mt20">
  17.                                 <thead>
  18.                                         <th>ID</th>
  19.                                         <th>Firstname</th>
  20.                                         <th>Lastname</th>
  21.                                         <th>Address</th>
  22.                                         <th>Action</th>
  23.                                 </thead>
  24.                                 <tbody id="tbody">
  25.                                 </tbody>
  26.                         </table>
  27.                 </div>
  28.         </div>
  29. </div>
  30.  
  31. <script src="asset/jquery.min.js"></script>
  32. <script src="asset/bootstrap/js/bootstrap.min.js"></script>
  33. <script src="asset/sweet_alert/sweetalert2.min.js"></script>
  34. <script src="asset/app.js"></script>
  35. </body>
  36. </html>

Creating our Ajax Scripts

Next, we the help of jQuery, we are going to create our ajax scripts. Create a new file inside our assets folder, name it as app.js and paste the codes below.

  1. $(document).ready(function(){
  2.         fetch();
  3.  
  4.         $(document).on('click', '.delete_product', function(){
  5.                 var id = $(this).data('id');
  6.  
  7.                 swal.fire({
  8.                         title: 'Are you sure?',
  9.                         text: "You won't be able to revert this!",
  10.                         icon: 'warning',
  11.                         showCancelButton: true,
  12.                         confirmButtonColor: '#3085d6',
  13.                         cancelButtonColor: '#d33',
  14.                         confirmButtonText: 'Yes, delete it!',
  15.                 }).then((result) => {
  16.                         if (result.value){
  17.                                 $.ajax({
  18.                                         url: 'api.php?action=delete',
  19.                                 type: 'POST',
  20.                                 data: 'id='+id,
  21.                                 dataType: 'json'
  22.                             })
  23.                             .done(function(response){
  24.                                 swal.fire('Deleted!', response.message, response.status);
  25.                                         fetch();
  26.                             })
  27.                             .fail(function(){
  28.                                 swal.fire('Oops...', 'Something went wrong with ajax !', 'error');
  29.                             });
  30.                         }
  31.  
  32.                 })
  33.  
  34.         });
  35. });
  36.  
  37. function fetch(){
  38.         $.ajax({
  39.                 method: 'POST',
  40.                 url: 'api.php',
  41.                 dataType: 'json',
  42.                 success: function(response){
  43.                         $('#tbody').html(response);
  44.                 }
  45.         });
  46. }

Creating our PHP API

Lastly, we create our PHP API where we put all our PHP functions. Create a new file, name it as api.php and paste the codes below.

  1. <?php
  2.         //connection
  3.         $conn = new mysqli('localhost', 'root', '', 'mydatabase');
  4.  
  5.         $action = 'fetch';
  6.  
  7.         if(isset($_GET['action'])){
  8.                 $action = $_GET['action'];
  9.         }
  10.  
  11.         if($action == 'fetch'){
  12.                 $output = '';
  13.                 $sql = "SELECT * FROM members";
  14.                 $query = $conn->query($sql);
  15.                 while($row = $query->fetch_assoc()){
  16.                         $output .= "
  17.                                 <tr>
  18.                                         <td>".$row['id']."</td>
  19.                                         <td>".$row['firstname']."</td>
  20.                                         <td>".$row['lastname']."</td>
  21.                                         <td>".$row['address']."</td>
  22.                                         <td><button class='btn btn-sm btn-danger delete_product' data-id='".$row['id']."'>Delete</button></td>
  23.                                 </tr>
  24.                         ";
  25.                 }
  26.  
  27.                 echo json_encode($output);
  28.         }
  29.  
  30.         if($action == 'delete'){
  31.                 $id = $_POST['id'];
  32.                 $output = array();
  33.                 $sql = "DELETE FROM members WHERE id = '$id'";
  34.                 if($conn->query($sql)){
  35.                         $output['status'] = 'success';
  36.                         $output['message'] = 'Member deleted successfully';
  37.                 }
  38.                 else{
  39.                         $output['status'] = 'error';
  40.                         $output['message'] = 'Something went wrong in deleting the member';
  41.                 }
  42.  
  43.                 echo json_encode($output);
  44.  
  45.         }
  46.  ?>

That's it you have now a simple delete function with sweet alert. By this you can make your end users experience a friendly and a better front-end experience.

Output Images:

Table Image

Table View

Delete Image

Delete Confirmation Popup Alert

Delete Image

Success Popup Alert

That ends this tutorial. Happy Coding :)

Add new comment