Ajax SweetAlert for Live Data Deleting Rows in with PHP~MySQL~Ajax

Ajax SweetAlert for Live Data Deleting Rows in with PHP MySQL Ajax

Ajax SweetAlert for Live Data Deleting Rows

Ajax Delete Example with SweetAlert2 to erase columns from MySQL table and utilize SweetAlert as Confirm exchange, So here In this instructional exercise, I am will demonstrate to you the most well-known erasing procedure of muck yet with the new usefulness by utilizing SweetAlert as an affirm discourse, we as of now have an instructional exercise about Ajax Delete with Bootstrap Confirmation Dialog you can check it. folks as all of you realize that default JavaScript affirms exchange is bad with regards to great UI/UX, so it’s great to utilize bootstrap or SweetAlert rather and it’s very simple to supplant default JavaScript PopUp discoursed. before continue please check a demo, So we should begin.

Live Demo   Download Source Code

database.sql

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


--
-- Database: `dbtest`
--

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

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

CREATE TABLE `tbl_products` (
  `product_id` int(11) NOT NULL,
  `product_name` varchar(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

INSERT INTO `tbl_products` (`product_id`, `product_name`) VALUES
(1, 'PHP'),
(2, 'HTML'),
(3, 'Javascript'),
(4, 'Jquery'),
(5, 'Ajax'),
(6, 'Angular'),
(7, 'Wordpress');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

dbconfig.php

<?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());
	}

index.php

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax SweetAlert for Live Data Deleting Rows in with PHP~MySQL~Ajax</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="https://www.lisenme.com/">
Ajax SweetAlert for Live Data Deleting Rows in with PHP~MySQL~Ajax</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: "It will be deleted permanently!",
			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>

read.php

<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>Application</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>

delete.php

<?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);
	}

 

You May Also Like

About the Author: Ranjith Kumar A

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Navin dagar
2 years ago

i was searching reply for this from many days but finally i found it quit good for me. thanks a lot to admin.

diego
diego
2 years ago

Segui el ejemplo tal cual pero, Me muestra la alerta, pero no elimina el registro..

2
0
Would love your thoughts, please comment.x
()
x