Hướng dẫn
Quảng cáo

Tích hợp Sweetalert 2 trong PHP & MySQL bằng Ajax

Hướng dẫn cách tích hợp Sweetalert 2 trong PHP & MySQL bằng Ajax thông qua ví dụ cụ thể

Trong các bài trước Ví dụ về PHP & MySQL AJAX Sử dụng jQueryEdit/Update/Delete dữ liệu trong PHP & MySQL bằng Ajax các thông báo hiển thị chúng ta đều sử dụng alert để thông báo, cảnh báo. Trong hướng dẫn này, mình sẽ chỉ cho bạn cách tích hợp sweetalert 2 trong PHP & MySQL bằng Ajax. Sweet alert 2 cho phép chúng ta tùy chỉnh hộp cảnh báo trong các ứng dụng web của chúng ta và giao diện thật tuyệt vời khiến nhiều nhà phát triển yêu thích nó. Vì vậy, trong bài viết này, mình sẽ chia sẻ cách tích hợp nó dễ dàng vào các ứng dụng của chúng ta.

Tập tin index.html

Thêm các tập tin css và js của Sweetalert 2 vào trong tập tin index.html của chúng ta ở các ví dụ trước. Dưới đây là mã đầy đủ của mình:

Ví dụ

<!doctype html>
<html lang="en">
<head>
  	<title>Ví dụ về PHP & MySQL AJAX Sử dụng jQuery</title>

  	<!-- Bootstrap CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  	<!-- sweetalert2 CSS -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.3.3/sweetalert2.css">
  	
  	<!-- Page CSS -->
  	<style type="text/css">
		.list-email {
			font-style: italic;
		}

		.list-address {
			margin-top: -14px;
		    margin-bottom: 0px;
		    font-size: 12px;
		}  		
  	</style>
</head>
  
<body>
   
	<div class="container">

		<br><br>

	    <h1>Ví dụ về PHP & MySQL AJAX Sử dụng jQuery</h1>

	    <br><br>
	    
	    <div class="row">
	    	<div class="col-md-4">
	    		<h3>Thêm nhân viên mới</h3>

			    <form action="save.php" id="form">
			    	<div class="form-group">
					    <label for="email">Email</label>
					    <input class="form-control" type="text" name="email">
				  	</div>
				  	<div class="form-group">
					    <label for="name">Họ và tên</label>
					    <input class="form-control" type="text" name="name">
				  	</div>
				  	<div class="form-group">
					    <label for="salary">Lương</label>
					    <input class="form-control" type="text" name="salary">
				  	</div>
				  	<div class="form-group">
					    <label for="address">Địa chỉ</label>
					    <textarea class="form-control" type="text" name="address" rows="3"></textarea>
				  	</div>
				  	<button type="button" class="btn btn-primary" id="btnSubmit">Gửi</button>
				</form>
	    	</div>

	    	<div class="col-md-8">
	    		<h3>Danh sách nhân viên</h3>
	    		<div id="employees-list"></div>
	    	</div>
	    </div>
	</div>
<!-- Modal hiển thị thông tin nhân viên để chỉnh sửa -->
	<div class="modal" id="edit-employee-modal">
	  	<div class="modal-dialog">
		    <div class="modal-content">

		      	<!-- Modal Header -->
		      	<div class="modal-header">
			        <h4 class="modal-title">Chỉnh sửa nhân viên</h4>
			        <button type="button" class="close" data-dismiss="modal">&times;</button>
		      	</div>

		      	<!-- Modal body -->
		      	<div class="modal-body">
		        	<form action="update.php" id="edit-form">
		        		<input class="form-control" type="hidden" name="id">
				    	<div class="form-group">
						    <label for="email">Email</label>
						    <input class="form-control" type="text" name="email">
					  	</div>
					  	<div class="form-group">
						    <label for="name">Họ và tên</label>
						    <input class="form-control" type="text" name="name">
					  	</div>
					  	<div class="form-group">
						    <label for="salary">Lương</label>
						    <input class="form-control" type="text" name="salary">
					  	</div>
					  	<div class="form-group">
						    <label for="address">Địa chỉ</label>
						    <textarea class="form-control" type="text" name="address" rows="3"></textarea>
					  	</div>
					  	<button type="button" class="btn btn-primary" id="btnUpdateSubmit">Cập nhật</button>
					  	<button type="button" class="btn btn-danger float-right" data-dismiss="modal">Đóng</button>
					</form>


		      	</div>

		    </div>
	  	</div>
	</div>
	<!-- Nên đặt các tệp javascript ở đây để tải trang nhanh hơn -->
	
	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
	<!-- Bootstrap JS -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
	<!-- sweetalert2 JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.3.3/sweetalert2.min.js"></script>
	<!-- Page Script -->
	<script type="text/javascript">
function all() 
{
	// Cài đặt Ajax
	$.ajax({
        type: "GET", //Phương thức nhận dữ liệu từ máy chủ
        url: 'all.php', // địa chỉ nhận dữ liệu
        success: function (response) {//dữ liệu được trả về tại đây
            
            // Phân giải kết quả Json
        	response = JSON.parse(response);

            var html = "";
            // Kiểm tra xem có kết quả hay không
            if(response.length) {
            	html += '<div class="list-group">';
	            // Tạo vòng lặp kết quả JSON
	            $.each(response, function(key,value) {
	            	// Danh sách nhân viên
					html += '<a href="#" class="list-group-item list-group-item-action">';
					html += "<p>" + value.name +' ('+ value.salary + ") <span class='list-email'>(" + value.email + ")</span>" + "</p>";
					html += "<p class='list-address'>" + value.address + "</p>";
					html += "<button class='btn btn-sm btn-primary mt-2' data-toggle='modal' data-target='#edit-employee-modal' data-id='"+value.id+"'>Sửa</button>";
					html += "<button class='btn btn-sm btn-danger mt-2 btn-delete-employee' data-id='"+value.id+"'>Xóa</button>";
					html += '</a>';
	            });
	            html += '</div>';
            } else {
            	html += '<div class="alert alert-warning">';
				  html += 'Không có dữ liệu!';
				html += '</div>';
            }

            

            // Hiển thị danh sách nhân viên
			$("#employees-list").html(html);
        }
    });
}

function submitForm() 
{
	$("#btnSubmit").on("click", function() {
		var $this 		    = $("#btnSubmit"); 
        var $caption        = $this.html();
        var form 			= "#form"; 
        var formData        = $(form).serializeArray();
        var route 			= $(form).attr('action'); 

        // Ajax config
    	$.ajax({
	        type: "POST", 
	        url: route, 
	        data: formData, 
	        beforeSend: function () {
	            $this.attr('disabled', true).html("Processing...");
	        },
	        success: function (response) {
	            $this.attr('disabled', false).html($caption);

	            // làm mới danh sách nhân viên
	            all();

	            // Hiển thông báo nhân viên thêm mới thành công
	            // alert(response);
	            Swal.fire({
				  icon: 'success',
				  title: 'Thành công.',
				  text: response
				});

	            // Làm mới biểu mẫu nhập dữ liệu
	            resetForm();
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	        	// Thông báo lỗi
	        }
	    });
	});
}

function resetForm() 
{
	$('#form')[0].reset();
}

function get() 
{
	$(document).delegate("[data-target='#edit-employee-modal']", "click", function() {

		var employeeId = $(this).attr('data-id');

		// Cài đặt Ajax
		$.ajax({
	        type: "GET", //Sử dụng phương thức get
	        url: 'get.php', // địa chỉ nhận dữ liệu
	        data: {employee_id:employeeId}, //thiết lập dữ liệu
	        beforeSend: function () {
	            
	        },
	        success: function (response) {//kết quả sẽ được trả về tại đây
	            response = JSON.parse(response);
	            $("#edit-form [name=\"id\"]").val(response.id);
	            $("#edit-form [name=\"email\"]").val(response.email);
	            $("#edit-form [name=\"name\"]").val(response.name);
	            $("#edit-form [name=\"salary\"]").val(response.salary);
	            $("#edit-form [name=\"address\"]").val(response.address);
	        }
	    });
	});
}

function update() 
{
	$("#btnUpdateSubmit").on("click", function() {
		var $this 		    = $(this); 
        var $caption        = $this.html();
        var form 			= "#edit-form"; 
        var formData        = $(form).serializeArray();
        var route 			= $(form).attr('action');

        // Cài đặt Ajax
    	$.ajax({
	        type: "POST",
	        url: route, 
	        data: formData,
	        beforeSend: function () {
	            $this.attr('disabled', true).html("Processing...");
	        },
	        success: function (response) {
	            $this.attr('disabled', false).html($caption);

	            all();

	            // Thông báo kết quả
	            // alert(response);
	            Swal.fire({
				  icon: 'success',
				  title: 'Thành công.',
				  text: response
				});

	            resetForm(form);

	            // Đóng modal
	            $('#edit-employee-modal').modal('toggle');
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	        	// Thông báo lỗi
	        }
	    });
	});
}
function del() 
{
	$(document).delegate(".btn-delete-employee", "click", function() {

		/*if (confirm("Bạn có chắc chắn muốn xóa dữ liệu nhân viên này?")) {
		    var employeeId = $(this).attr('data-id'); //lấy ID nhân viên

		    // Cài đặt Ajax
			$.ajax({
		        type: "GET", 
		        url: 'delete.php',
		        data: {employee_id:employeeId}, 
		        beforeSend: function () {
		            
		        },
		        success: function (response) {
	            	all();

		            alert(response)
		        }
		    });
		}*/
		Swal.fire({
			icon: 'warning',
		  	title: 'Bạn có chắc chắn muốn xóa dữ liệu nhân viên này?',
		  	showDenyButton: false,
		  	showCancelButton: true,
		  	confirmButtonText: 'Yes'
		}).then((result) => {
		  /* Read more about isConfirmed, isDenied below */
		  if (result.isConfirmed) {

		  	var employeeId = $(this).attr('data-id');

		  	// Ajax config
			$.ajax({
		        type: "GET", 
		        url: 'delete.php', 
		        data: {employee_id:employeeId},
		        beforeSend: function () {
		            
		        },
		        success: function (response) {
	            	all();

		            Swal.fire('Thành công.', response, 'success')
		        }
		    });

		    
		  } else if (result.isDenied) {
		    Swal.fire('Thay đổi không được lưu', '', 'info')
		  }
		});		
	});
}
$(document).ready(function() {

	// Lấy danh sách nhân viên
	all();

	// Sử dụng AJAX để gửi biểu mẫu
	submitForm();

	// Lấy dữ liệu nhân viên hiển thị lên modal
	get();
	 
	// Cập nhật dữ liệu nhân viên
	update();
	// Xóa dữ liệu bằng Ajax
	del();
	 
});		
	</script>

</body>
  
</html>

Trong đó các bạn có thể thấy tất cả các cảnh báo (alert) thành công mình đều đã thay đổi thành:

Ví dụ

Thông báo mới Thông báo cũ
Swal.fire({
				  icon: 'success',
				  title: 'Thành công.',
				  text: response
				});
alert(response);

Và với chắc năng xóa nhân viên thì mã js đã được thay đổi như dưới.

Ví dụ

Mã mới Mã cũ
function del() 
{
	$(document).delegate(".btn-delete-employee", "click", function() {
		Swal.fire({
			icon: 'warning',
		  	title: 'Bạn có chắc chắn muốn xóa dữ liệu nhân viên này?',
		  	showDenyButton: false,
		  	showCancelButton: true,
		  	confirmButtonText: 'Yes'
		}).then((result) => {
		  if (result.isConfirmed) {

		  	var employeeId = $(this).attr('data-id');

		  	// Ajax config
			$.ajax({
		        type: "GET", 
		        url: 'delete.php', 
		        data: {employee_id:employeeId},
		        beforeSend: function () {
		            
		        },
		        success: function (response) {
	            	all();

		            Swal.fire('Thành công.', response, 'success')
		        }
		    });

		    
		  } else if (result.isDenied) {
		    Swal.fire('Thay đổi không được lưu', '', 'info')
		  }
		});		
	});
}
function del() 
{
	$(document).delegate(".btn-delete-employee", "click", function() {

		if (confirm("Bạn có chắc chắn muốn xóa dữ liệu nhân viên này?")) {
		    var employeeId = $(this).attr('data-id'); //lấy ID nhân viên

		    // Cài đặt Ajax
			$.ajax({
		        type: "GET", 
		        url: 'delete.php',
		        data: {employee_id:employeeId}, 
		        beforeSend: function () {
		            
		        },
		        success: function (response) {
	            	all();

		            alert(response)
		        }
		    });
		}		
	});
}

Với Sweetalert 2 thì các cảnh báo của bạn nhìn trong nó chuyên nghiệp và đẹp mắt hơn nhiều!

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements