Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

Effectively using sweetalert confirm and cancel

I have this code to run when i click the delete button:

$(document).on('click', '.remove', function (e) {
         e.preventDefault();
         var id = $(this).data('id');

         $.ajax({
            type: "POST",
            url: "<?php echo Yii::$app->request->baseUrl;?>"+'/todo/deletetask',
            data: {id:id},
            success: function (data) {
                var res = $.parseJSON(data);
                if(res != false) {
                    swal({
                            title: "Are you sure!",
                            type: "error",
                            confirmButtonClass: "btn-danger",
                            confirmButtonText: "Yes!",
                            showCancelButton: true,
                            },
                            function(){

                                       window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
                       });         
               }
            }
        });          
    });

and the controller action is:

public function actionDeletetask()
    {
        if(Yii::$app->request->isAjax)
        {
            $id = $_POST['id'];
            if($id)
                {
                    Todo::find()->where(['todo_id'=>$id])->one()->delete();    
                }

                echo json_encode(TRUE);die;
        }

        echo json_encode(FALSE);die;

    }

but even if i click the sweet alert cancel button, the task is deleted, which is obvious.but how can i prevent it?

Upvotes: 2

Views: 31748

Answers (3)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

As of version 2.x, there have been changes, that would throw an error for 2nd argument, for the function that is passed. Instead of this, the promise or async/await should be used.

see: https://github.com/t4t5/sweetalert#a-warning-message-with-a-function-attached-to-the-confirm-message

Also, there is the deprecation of showCancelButton, confirmButtonText, cancelButtonText, closeOnConfirm, etc. in favor of button and buttons objects along with their options.

see: https://sweetalert.js.org/docs/#button and https://sweetalert.js.org/docs/#buttons

Considering these changes in version 2.x, the code using the promise should look like this:

$(document).on('click', '.remove', function (e) {
    e.preventDefault();
    var id = $(this).data('id');
    // Show the user a swal confirmation window
    swal({
            title: "Are you sure?",
            icon: "error",
           // dangerMode: true, //set this in case the focus should be on cancel button
            buttons: [true, "Yes!"] //for detailed options see on https://sweetalert.js.org/docs/#buttons
        }).then( isConfirmed => {
            if(isConfirmed){
                // This function will run ONLY if the user clicked Yes!
                // Only here we want to send the request to the server!
                $.ajax({
                    type: "POST",
                    url: "<?php echo Yii::$app->request->baseUrl;?>" + '/todo/deletetask',
                    data: {id:id},
                    success: function (data) {
                        var res = $.parseJSON(data);
                        if(res !== false) {
                            swal("Task Deleted", "", "success")
                        }
                    }
                });
            }else{
                // This function will run if the user clicked "cancel"
                window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
            }
    });

});

Upvotes: 1

Dekel
Dekel

Reputation: 62536

The problem that you have with your code is that currently, when you click on the button - the code will send the request of todo/deletetask to your server, and only when the request is done (the task was deleted) you show the user the confirm message.

Instead - what you should do is show the user the confirmation message when he clicks on the button - and only if the user has confirmed the deletion of the task - you need to send the todo/deletetask request to the server.

Here is your code fixed with the new logic:

$(document).on('click', '.remove', function (e) {
    e.preventDefault();
    var id = $(this).data('id');
    // Show the user a swal confirmation window
    swal({
            title: "Are you sure!",
            type: "error",
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes!",
            showCancelButton: true,
        },
        function() {
            // This function will run ONLY if the user clicked "ok"
            // Only here we want to send the request to the server!
            $.ajax({
                type: "POST",
                url: "<?php echo Yii::$app->request->baseUrl;?>"+'/todo/deletetask',
                data: {id:id},
                success: function (data) {
                    var res = $.parseJSON(data);
                    if(res != false) {
                        swal("Task Deleted", "", "success")
                    }
                }
            });
        },
        function() {
            // This function will run if the user clicked "cancel"
            window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
        }
    );
});

Upvotes: 9

T.J. Crowder
T.J. Crowder

Reputation: 1074088

Right there on the front page of the sweetalert site, it shows that if you include a cancel button, your callback gets an argument saying whether the action was confirmed or cancelled; from that page:

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");
    }
});

So accept the argument as shown above and only do the deletion if it's truthy.

Upvotes: 11

Related Questions