Use SweetAlert For Form Confirmation Dialog - HTML & Javascript

Use SweetAlert For Form Confirmation – HTML & Javascript

In this tutorial, we are going to show you, how you can show a sweetalert confirmation dialog when submitting a form. For example, if you have a form that when submits delete the data from database. In that case, you must verify from the user because he might click that button by accident. So you can show a nice dialog using Sweetalert library. Suppose you have the following form:

<form method="POST" action="do-something.php" onsubmit="return submitForm(this);">
	<input type="text" name="name" />
	<input type="submit" />
</form>

When the form submits, we are calling a Javascript function submitForm and passing the form as a parameter. Then you need to download the Sweetalert library from here. After downloading, paste that in your project and include it in your HTML file:

<script src="sweetalert.min.js"></script>

Now, we can create that Javascript function that will ask for confirmation. Once confirmed, it will submit the form.

<script>
	function submitForm(form) {
		swal({
			title: "Are you sure?",
			text: "This form will be submitted",
			icon: "warning",
			buttons: true,
			dangerMode: true,
		})
		.then(function (isOkay) {
			if (isOkay) {
				form.submit();
			}
		});
		return false;
	}
</script>

All the form fields will be submitted correctly on the server-side. You can check it by printing out all the values received from the form:

<?php

print_r($_POST);

Leave a Reply

Please disable your adblocker or whitelist this site!