jQuery Confirm3 $.confirm nor returning boolean neither expected result

102 Views Asked by At

I have 2 functions related to each other .. _confirm and _process. _confirm is responsible for returning true/false values to _process and based on response _process function will act and process the bid.

BUT THE ISSUE IS: that the within _process the _confirm is returning undefined rather showing boolean, because it's moving on before data from _confirm

NOTE* using jquery-confirm-3 library for alert/confirm

<script type="text/javascript">

/* Extra confirmation message on place bid */
function _confirm( formname, id_Bid ) {

    var response = '';

    /* Get bid value, format value and then add to confirm message */
    var bidval = jQuery(id_Bid).val();
    var bidval = parseFloat(bidval);

    if ( bidval > 0 ) {

        var floatbidval = bidval.toFixed(2);
        var currencyval = "$";
        var finalval = currencyval + floatbidval;

        if( formname == 'custom' ) {
            var confirm1 = 'Do you really want to bid';
        } else if( formname == 'direct' ){
            var confirm1 = 'Do you really want to directly place this bid';
        }

        let confirm_message = confirm1 + ' ' + finalval + ' ?';

         $.confirm({
            title: false,
            content: confirm_message,
            onAction: function( btnName ) {
                response = btnName;
            },
            buttons: {
                confirm: function () {},
                cancel: function () {}
            }
        });

        if( response != 'confirm' ) {
            event.preventDefault();
            return false;
        } else{
            return true;
        }
    }

} /* end of function - _confirm() */

function _process( formname, id_Bid ) {

    <?php
    $enable_bid_place_warning = get_option('uwa_enable_bid_place_warning');
    $placebid_ajax_enable = get_option('woo_ua_auctions_placebid_ajax_enable');

    /* using page load */
    if( $placebid_ajax_enable == 'no' || $placebid_ajax_enable == '' ) {
        if( $enable_bid_place_warning  == 'yes' ) { ?>
            $data = _confirm( formname, id_Bid ); <?php
        }
    } elseif ( $placebid_ajax_enable == 'yes' ) { /* using ajax */
        if( $enable_bid_place_warning  == 'yes' ) { ?>

            retval = _confirm( formname, id_Bid );

            if( retval == true ) {
                place_ajax_process( formname );
            } <?php
        } else { ?>
            place_ajax_process( formname );
        <?php
        }
    }
    ?>

} /* end of function */
</script>

Later researching here, I found a couple of answers to use .Deferred() and return a promise .. but the promise is also returning unidentified

later I made the following changes but still no luck

    function _showConfirmDialog( message ) {
        let def = $.Deferred();
        $.confirm({
            title: false,
            content: message,
            onAction: function( btnName ) {
                def.resolve(btnName);
            },
            buttons: {
                confirm: function () {},
                cancel: function () {}
            }
        });
        def.promise();
    }

    /* Extra confirmation message on place bid */
    function _confirm( formname, id_Bid ) {

        var response = '';

        /* Get bid value, format value and then add to confirm message */
        var bidval = jQuery(id_Bid).val();
        var bidval = parseFloat(bidval);

        if ( bidval > 0 ) {

            var floatbidval = bidval.toFixed(2);
            var currencyval = "$";
            var finalval = currencyval + floatbidval;

            if( formname == 'custom' ) {
                let confirm1 = 'Do you really want to bid';
            } else if( formname == 'direct' ){
                let confirm1 = 'Do you really want to directly place this bid';
            }

            let confirm_message = confirm1 + ' ' + finalval + ' ?';

            $.when(_showConfirmDialog(confirm_message)).then(function( response ) {
                if ( response == 'confirm' ) {
                    return true;
                } else {
                    return false;
                }
            });
        }

    }

i also tried to use async and await but no luck.

2

There are 2 best solutions below

3
Roamer-1888 On

You are nearly there with your second attempt but _showConfirmDialog() needs to return Promise. It currently returns undefined.

You should also consider exploiting the promise's settled state (resolved/rejected) rather than resolving with btnName. Thus the code is more independent of natural language.

You might write:

function _showConfirmDialog(message) {
    return $.Deferred(function(dfrd) {
    ^^^^^^
        $.confirm({
            'title': false,
            'content': message,
            'buttons': {
                'confirm': dfrd.resolve, // resolve on confirm
                'cancel': dfrd.reject // reject on cancel
            }
        });
    }).promise();
}

Similarly, _confirm() should also return promise in order to keep its caller informed of the dialog's outcome.

You might write:

function _confirm(formname, id_Bid) {
    var bidval = parseFloat(jQuery(id_Bid).val());
    if (bidval > 0) {
        if (formname == 'custom') {
            let confirm1 = 'Do you really want to bid';
        } else if (formname == 'direct') {
            let confirm1 = 'Do you really want to directly place this bid';
        } else { // unconditional else
            // what if formname is neither 'custom' nor 'direct'
        }
        return _showConfirmDialog(`${confirm1} $${bidval.toFixed(2)} ?`);
        ^^^^^^
    }
}

Thus, _confirm() returns a promise that will resolve if the user clicks "confirm" or rejects if the user clicked "cancel" (rather than resolving wirth true|false).

Note: Unless there's a compelling reason to want a jQuery promise, it's better to Promisify jQuery.confirm() with a native JS Promise.

You might write:

function _showConfirmDialog(message) {
    return new Promise(function(resolve, reject) {
    ^^^^^^ ^^^^^^^^^^^
        $.confirm({
            'title': false,
            'content': message,
            'buttons': {
                'confirm': resolve, // resolve on confirm
                'cancel': function() { // reject on cancel
                    reject(new Error('confirm dialog cancelled'));
                }
            }
        });
    });
}

Thus, _confirm() (as above) will also return a native Promise.

3
Muzammil Hussain On

You are right @Roamer-1888

and I will impose the changes you applied in your code, anywho i would like to show the changes I made in my code before you post

function _showConfirmDialog( message ) {
    let def = $.Deferred();
    $.confirm({
        title: false,
        content: message,
        draggable: false,
        theme: 'modern',
        // icon: 'dashicons dashicons-format-chat',
        boxWidth: '30%',
        useBootstrap: false,
        onAction: function( btnName ) {
            def.resolve(btnName);
        },
        buttons: {
            confirm: function () {},
            cancel: function () {}
        }
    });
    return def;
    ^^^^^^^^^^
}

Previously I was returning def.Promise() which was causing the issue. then when I use this function i awaited

async function confirm_bid( formname, id_Bid ) {
^^^^^
    ... (code block)
    
    await _showConfirmDialog(confirm_message).then(function (res) {
    ^^^^^
        if ( res == 'confirm' ) {
            response = true
        } else {
            response = false;
        }
    });
}

and lastly where ever I use confirm_bid() function i added await with async

async function bid_process( formname, id_Bid ) {
^^^^^

    ...( other code )

    retval = await confirm_bid( formname, id_Bid );
             ^^^^^
    if( retval == true ) {
        /* bid using ajax if confirm yes */
        placebid_ajax_process( formname );
    }

    ...( other code )
    
}