dmeehan dmeehan - 1 year ago 147
Javascript Question

Page is not waiting for response from javascript Sweet Alert

I am trying to upgrade my javascript confirm() action to use Sweet Alert ( Currently my code is something like this:

<a href="/delete.php?id=100" onClick="return confirm('Are you sure ?');" >Delete</a>

This waits for the user to confirm before navigating to the delete page. I would like to use this example from Sweet Alert to ask the user to confirm before deleting:

title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
else {
swal("Cancelled", "Your imaginary file is safe :)", "error");

Everything I have tried has failed. When the first alert is displayed, the page has gone ahead and deleted the item and refreshed before the user has even clicked on the alert buttons. How do I make the page wait for the users input?

Any help would be greatly appreciated.

Answer Source

You cannot use this as a drop-in replacement for confirm. confirm blocks the single thread of execution until the dialog has been acknowledged, you cannot produce the same behavior with a JavaScript/DOM-based dialog.

You need to issue a request to /delete.php?id=100 in the success callback for your alert box.

Instead of...

swal("Deleted!", "Your imaginary file has been deleted.", "success");

You need

<a href="#">Delete<a>

$.post('/delete.php?id=100').then(function () {
  swal("Deleted!", "Your imaginary file has been deleted.", "success");

You also must fix your delete.php to only accept POST requests. It's a huge problem to allow GET requests to delete resources. The first time Google or any other crawler finds your page, it will look at the href of every link in your document and follow each link, deleting all of your content. They will not be stopped by the confirm box, as they probably (with the exception of Google) won't be evaluating any JavaScript.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download