Magento 2 Confirmation Widget – Confirm Action

confirmationmagento2widget

I'm trying to execute a function on confirm widget confirmation, but the confirm action is firing on load page always.

Here is the HTML:

<a class="action accept" id="accept_user" href="#">
    <span>
        <?php /* @escapeNotVerified */ echo __('Accept'); ?>
    </span>
</a>

And Here the JS:

<script>
require([
        'jquery',
        'Magento_Ui/js/modal/confirm'
    ],
    function($, confirmation) {
        $('#accept_user').on('click', function (e){
            e.preventDefault();
            confirmation({
                title: 'Accept user',
                content: 'Do you want to accept this user?',
                actions: {

                    confirm: function () {
                        <?php /* @escapeNotVerified */ echo $block->activateUser('$userId'); ?>
                    },

                    cancel: function () {
                        return false;
                    }
                }
            });
        });
    });
</script>

How to execute the confirm action only when user click on Accept button from confirmation modal?

It's for frontend area.

Thank you!!

Best Answer

This is because you have called echo $block->activateUser('$userId'); inside it. The correct way should be if you call ajax to a controller and put your logic for activateUser in it. Something like this:

<script>
require([
    'jquery',
    'Magento_Ui/js/modal/confirm'
],
function($, confirmation) {
    $('#accept_user').on('click', function (e){
        e.preventDefault();
        confirmation({
            title: 'Accept user',
            content: 'Do you want to accept this user?',
            actions: {

                confirm: function () {
                    $.ajax({
                         showLoader: true,
                         url: 'route-for-controller',
                         data: {},
                         type: "POST",
                         success: function (data) {
                                 console.log(data);
                                 <!-- things you want to perform on success or you can relaod the page to show changes -->
                            },
                         error: function (error) {

                                     }
                    });
                },

                cancel: function () {
                    return false;
                }
            }
        });
    });
});