SweetAlert2 – Ajax Delete Rows Example with PHP MySQL | Coding Cage

SweetAlert2 – Ajax Delete Rows Example with PHP MySQL

By
Hello coders, In our previous tutorial we saw all about getting started with SweetAlert2 and regarding it I also receive few emails to post Ajax Delete Example with SweetAlert2 to delete rows from MySQL table and use SweetAlert as Confirm dialog, So here In this tutorial, I am going to show you the most common deleting process of crud but with the new functionality by using SweetAlert as a confirm dialog, we already have a tutorial about Ajax Delete with Bootstrap Confirmation Dialog you can check it. guys as you all know that default JavaScript confirm dialog is not very good when it comes to impressive UI/UX, so it's good to use bootstrap or SweetAlert instead and it's quite easy to replace default JavaScript PopUp dialogs. before proceed please check a demo, So let’s get started.
SweetAlert2 – Ajax Delete Rows Example with PHP MySQL





Database & Table

The database, table and dumbing data are the same which i have used in this tutorial : Ajax Delete Bootstrap Confirm Modal with PHP. so you just have to copy paste the following sql code in your phpMyAdmin to create table.

--
-- Database: `dbtest`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_products`
--

CREATE TABLE IF NOT EXISTS `tbl_products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(35) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

--
-- Dumping data for table `tbl_products`
--

INSERT INTO `tbl_products` (`product_id`, `product_name`) VALUES
(1, 'Galaxy Jmax'),
(2, 'Killer Note5'),
(3, 'Asus ZenFone2'),
(4, 'Moto Xplay'),
(5, 'Lenovo Vibe k5 Plus'),
(6, 'Redme Note 3'),
(7, 'LeEco Le 2'),
(8, 'Apple iPhone 6S Plus');

Database Configuration

this is database configuration file contains PHP code which creates the connection with MySQL, of course you know that, save it as dbconfig.php, now let's move.
<?php
 
 $DBhost = "localhost";
 $DBuser = "root";
 $DBpass = "";
 $DBname = "dbtest";
 
 try {
  $DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
  $DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 } catch(PDOException $ex){
  die($ex->getMessage());
 }




getting/ selecting data from products table

Here is the Simple code to display the product details from MySQL tbl_products table, the last action column is for data deleting with anchor tag along with HTML5 custom Data Attribute data-id which stores product id and this will trigger out by delete_product id using jQuery's click event, using this we can get the product id to get deleted from table, this is read.php page.

<div class="table-responsive">
<table class="table table-bordered table-condensed table-hover table-striped" cellspacing="0" width="100%">
<thead>
   <tr>
   <th>#ID</th>
   <th>Product Name</th>
   <th>Action</th>
   </tr>
</thead>
<tbody>
<?php
   require_once 'dbconfig.php';
   $query = "SELECT product_id, product_name FROM tbl_products";
   $stmt = $DBcon->prepare( $query );
   $stmt->execute();
   if($stmt->rowCount() > 0) {
 while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
 extract($row);
 ?>
 <tr>
 <td><?php echo $product_id; ?></td>
        <td><?php echo $product_name; ?></td>
 <td> 
 <a class="btn btn-sm btn-danger" id="delete_product" data-id="<?php echo $product_id; ?>" href="javascript:void(0)"><i class="glyphicon glyphicon-trash"></i></a>
 </td>
 </tr>
 <?php
        } 
   } else {
 ?>
        <tr>
        <td colspan="3">No Products Found</td>
        </tr>
        <?php
   }
?>
</tbody>
</table>   
</div>

Showing/Display Data

Ok, now we have a "read.php" file which contains MySQL data in table format, now we just have to load read.php file within index page to display. by using jQuerie's load() function.

<!-- read.php files table will be load in this div -->
<div id="load-products"></div>

<!-- javascript function to load read.php file -->
function readProducts(){
   $('#load-products').load('read.php'); 
}

SweetAlert Confirm Delete Dialog

Here comes SweetAlert and i already posted a tutorial on how to use so i come to the point and shows you confirm dialog.
swal({
   title: 'Are you sure?',
   text: "You won't be able to revert this!",
   type: 'warning',
   showCancelButton: true,
   confirmButtonColor: '#3085d6',
   cancelButtonColor: '#d33',
   confirmButtonText: 'Yes, delete it!',
   showLoaderOnConfirm: true,
   preConfirm: function() {
     return new Promise(function(resolve) {
     /*
     Ajax code will be here
     */
     });
   },
   allowOutsideClick: false     
});

Ajax Deleting Code

This is simple ajax code which should be within SweetAlert's Promise function and it will take care of deleting process.
$.ajax({
   url: 'delete.php',
   type: 'POST',           
   data: 'delete='+productId,
   dataType: 'json'
})
.done(function(response){
   swal('Deleted!', response.message, response.status);
   readProducts();
})
.fail(function(){
   swal('Oops...', 'Something went wrong with ajax !', 'error');
});

PHP Code to delete records.

create a delete.php file and put following code inside it.
<?php
header('Content-type: application/json; charset=UTF-8');
$response = array();
 
if ($_POST['delete']) {
 
    require_once 'dbconfig.php';
 
    $pid = intval($_POST['delete']);
    $query = "DELETE FROM tbl_products WHERE product_id=:pid";
    $stmt = $DBcon->prepare( $query );
    $stmt->execute(array(':pid'=>$pid));
    
    if ($stmt) {
        $response['status']  = 'success';
 $response['message'] = 'Product Deleted Successfully ...';
    } else {
        $response['status']  = 'error';
 $response['message'] = 'Unable to delete product ...';
    }
    echo json_encode($response);
}

SwalDelete() : Function to Handle Ajax SweetAlert Delete

This is complete custom SwalDelete() function which handles deleting process via ajax request along with SweetAlert confirm dialog.
function SwalDelete(productId){
   swal({
   title: 'Are you sure?',
   text: "You won't be able to revert this!",
   type: 'warning',
   showCancelButton: true,
   confirmButtonColor: '#3085d6',
   cancelButtonColor: '#d33',
   confirmButtonText: 'Yes, delete it!',
   showLoaderOnConfirm: true,
   preConfirm: function() {
      return new Promise(function(resolve) {
  $.ajax({
     url: 'delete.php',
     type: 'POST',
     data: 'delete='+productId,
     dataType: 'json'
  })
  .done(function(response){
     swal('Deleted!', response.message, response.status);
     readProducts();
         })
  .fail(function(){
     swal('Oops...', 'Something went wrong with ajax !', 'error');
  });
      });
   },
   allowOutsideClick: false     
   }); 
}

Trigger the SwalDelete() function.

all set, now we just have to make trigger the SwalDelete() function by using following code, here it is. when you click on delete button SwalDelete function will get id of that particular row and the rest process will happen. data-id attribute holds the id of product.
$(document).on('click', '#delete_product', function(e){
   var productId = $(this).data('id');
   SwalDelete(productId);
   e.preventDefault();
});

Index.php : Putting all together

following is the complete index.php file contains all above code together so that you won't get confused.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SweetAlert2 – Ajax Delete Rows Example with PHP MySQL</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="assets/swal2/sweetalert2.min.css" type="text/css" />
</head>
<body>

    <div class="container">
     
        <div class="page-header">
        <h1><a target="_blank" href="http://www.codingcage.com/2016/08/delete-rows-from-mysql-with-bootstrap.html">SweetAlert2 – Ajax Delete Rows Example with PHP MySQL</a></h1>
        </div>
        
        <div id="load-products"></div> <!-- products will be load here -->
    
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/swal2/sweetalert2.min.js"></script>


<script>
 $(document).ready(function(){
  
  readProducts(); /* it will load products when document loads */
  
  $(document).on('click', '#delete_product', function(e){
   
   var productId = $(this).data('id');
   SwalDelete(productId);
   e.preventDefault();
  });
  
 });
 
 function SwalDelete(productId){
  
  swal({
   title: 'Are you sure?',
   text: "You won't be able to revert this!",
   type: 'warning',
   showCancelButton: true,
   confirmButtonColor: '#3085d6',
   cancelButtonColor: '#d33',
   confirmButtonText: 'Yes, delete it!',
   showLoaderOnConfirm: true,
     
   preConfirm: function() {
     return new Promise(function(resolve) {
          
        $.ajax({
        url: 'delete.php',
        type: 'POST',
           data: 'delete='+productId,
           dataType: 'json'
        })
        .done(function(response){
         swal('Deleted!', response.message, response.status);
     readProducts();
        })
        .fail(function(){
         swal('Oops...', 'Something went wrong with ajax !', 'error');
        });
     });
      },
   allowOutsideClick: false     
  }); 
  
 }
 
 function readProducts(){
  $('#load-products').load('read.php'); 
 }
 
</script>
</body>
</html>



Hope you guy's like this tutorial, and please don't forget to share this tutorial with you friends. if you are using bootstrap for your projects then you must use this, so download the code and try...



10 comments:

  1. merry christmas and thank

    ReplyDelete
    Replies
    1. you're welcome, and merry xmas to you too. :)

      Delete
  2. wow this is a nice tutorial please am new to json i dont really get the syntax i would prefer other method on the ajax call..
    Thanks

    ReplyDelete
    Replies
    1. yes of course you can use the method which you like for ajax call, BTW thanks for your comment. :)

      Delete
  3. Excellent tutorial thanks man
    keep publishing excellence like that

    ReplyDelete
    Replies
    1. Hi Maxamed Qadar,
      glad you liked it, thanks for visiting :)

      Delete
  4. great work man keep it up


    can you help me in making a search bar like youtube or other videos website search please help me

    ReplyDelete
  5. Thanks~
    Happy new year~

    ReplyDelete
  6. What you have written in this post is exactly what I have experience when I first started my blog.I’m happy that I came across with your site this article is on point,thanks again and have a great day.Keep update more information.

    Back to Original

    ReplyDelete
  7. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care.As always, we appreciate you confidence and trust in us.

    Dental Hospital In Chennai

    ReplyDelete