Azixy_codes
Azixy_codes

Reputation: 123

Uncaught SweetAlert: Unexpected 2nd argument?

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.

Upvotes: 12

Views: 26570

Answers (1)

5less
5less

Reputation: 970

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.

Upvotes: 19

Related Questions