Search code examples
laravelsweetalert2

Sweet Alert 2 redirect on CANCEL


I am writing a project in laravel, at my current point in the workflow I want the user to be able to click a button to publish or remove an event from the current list.

I am using SA2 to stop the submission to the route before it happens, if the user hits OK, then everything goes as planned, when the user hits cancel, I want to redirect back to the page.

The issue I am running in to is that when the user hits cancel, the redirect to the page happens anyway...

function warnRemove(linkURL) {
    swal({
        title: 'Are you sure?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: 'D6B55',
        confirmButtonText: 'Yes, remove it!'
    }).then(function () {
        window.location = linkURL;
    });
}

function warnPublish(linkURL) {
    swal({
        title: 'Are you sure?',
        type: 'warning',
        text: 'This event will go live on the screen after next refresh.',
        showCancelButton: true,
        confirmButtonColor: 'D6B55',
        confirmButtonText: 'Yes, publish it!'
    }).then(function () {
        window.location = linkURL;
    });
}



$('.remove').click(function(e) {
    e.preventDefault(); // Prevent the href from redirecting directly
    let linkURL = $(this).attr("href");
    warnRemove(linkURL);
});

$('.publish').click(function(e) {
    e.preventDefault(); // Prevent the href from redirecting directly
    let linkURL = $(this).attr("href");
    warnPublish(linkURL);
});

Solution

  • You will need to use the callback with an isConfirm boolean:

    function(isConfirm) {
        if (isConfirm) {
            // do confirmed things
        }
    }
    

    From the docs:

    swal({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      // redirect only if true
      if (result.value) {
        // redirect here
      }
    })