article

Friday, June 24, 2022

PHP MySQLi Delete Table Row using Sweetalert2

PHP MySQLi Delete Table Row using Sweetalert2

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

sweetalert2
https://sweetalert2.github.io/#download
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>How to Delete Table Row using Sweetalert2 with PHP/MySQLi</title>
	<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
	
	<link href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>

	<style type="text/css">
		.mt20{
			margin-top:20px;
		}
	</style>
</head>
<body>
<div class="container">
	<h1 class="text-center mt20">PHP MySQLi Delete Table Row using Sweetalert2 </h1>
	<div class="row justify-content-center">
		<div class="col-sm-8">
			<table class="table table-bordered mt20">
				<thead>
					<th>ID</th>
					<th>Firstname</th>
					<th>Lastname</th>
					<th>Address</th>
					<th>Action</th>
				</thead>
				<tbody id="tbody">
				</tbody>
			</table>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	fetch();
 
	$(document).on('click', '.btn_delete', function(){
		var id = $(this).data('id');
 
		swal.fire({
		  	title: 'Are you sure?',
		  	text: "You won't be able to revert this!",
		  	icon: 'warning',
		  	showCancelButton: true,
		  	confirmButtonColor: '#3085d6',
		  	cancelButtonColor: '#d33',
		  	confirmButtonText: 'Yes, delete it!',
		}).then((result) => {
		  	if (result.value){
		  		$.ajax({
			   		url: 'ajaxfile.php?action=delete',
			    	type: 'POST',
			       	data: 'id='+id,
			       	dataType: 'json'
			    })
			    .done(function(response){
			     	swal.fire('Deleted!', response.message, response.status);
					fetch();
			    })
			    .fail(function(){
			     	swal.fire('Oops...', 'Something went wrong with ajax !', 'error');
			    });
		  	}
 
		})
 
	});
});
 
function fetch(){
	$.ajax({
		method: 'POST',
		url: 'ajaxfile.php',
		dataType: 'json',
		success: function(response){
			$('#tbody').html(response);
		}
	});
}
</script>
</body>
</html>

Related Post