Uncaught SweetAlert: Unexpected 2nd argument?

Азиз Чеграни picture Азиз Чеграни · Oct 11, 2017 · Viewed 16.9k times · Source

I have a problem with sweetalert, I would like to show the confirm box alert on button click but it's not working

This is my JS code:

$(document).ready(function(){
$('[data-confirm]').on('click', function(e){
    e.preventDefault(); //cancel default action

//Recuperate href value
var href = $(this).attr('href');


var message = $(this).data('confirm');

//pop up
swal({
    title: "Are you sure ??",
    text: message, 
    type: "warning",
    showCancelButton: true,
    cancelButtonText: "Cancel",
    confirmButtonText: "confirm",
    confirmButtonColor: "#DD6B55"},

function(isConfirm){
    if(isConfirm) {
    //if user clicks on "confirm",
    //redirect user on delete page

    window.location.href = href;
    }
});
});
});

HTML:

<a data-confirm='Are you sure you want to delete this post ?' 
href="deletePost.php?id=<?= $Post->id ?>"><i class="fa fa-trash">
</i> Delete</a>

All required files are imported.

Answer

5less picture 5less · Oct 11, 2017

The code you are using is from prior the latest version 2. Please read up on Upgrading from 1.X.

You should use promise to keep track of user interaction.

Updated code

$(document).ready(function(){
    $('[data-confirm]').on('click', function(e){
        e.preventDefault(); //cancel default action

        //Recuperate href value
        var href = $(this).attr('href');
        var message = $(this).data('confirm');

        //pop up
        swal({
            title: "Are you sure ??",
            text: message, 
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
        .then((willDelete) => {
          if (willDelete) {
            swal("Poof! Your imaginary file has been deleted!", {
              icon: "success",
            });
            window.location.href = href;
          } else {
            swal("Your imaginary file is safe!");
          }
        });
    });
});

Notes

  • type have been replaced with icon option.
  • Replaced showCancelButton, CancelbuttonText, confirmButtonText and confirmButtonColor with only buttons.
  • dangerMode: true to make the confirm button red.