dmeehan dmeehan - 28 days ago 12
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 (http://t4t5.github.io/sweetalert/). 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:

swal({
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
},
function(isConfirm){
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

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.

Comments