Home > OS >  Run 2 functions synchronously in jQuery
Run 2 functions synchronously in jQuery

Time:12-28

In jQuery, I am using dialog for the user confirmation. But when I try to run this code shown here, it does not work as I want.

If the user selects "yes", then after another function like addeditrules() must execute/run. But currently I can not get any response from the ConfirmDialog() function.

Here is my code:

$(document).on('click', 'a[id*="editrulesave_"]', function() {
        var id = $(this).data('id');
        dataSerial = $('#editform_' id).serialize();
        var data = dataSerial  "&type=edit&id=" id;
        var url = "/adminRulesAddeEdit"
        var msg = 'Are you sure you want to save this rule!'
        var confirm ='';

        confirm = ConfirmDialog(msg)

        if (confirm == 'yes') {
            addeditrules(url,data)
        }
})

function ConfirmDialog(message) {
        $('<div></div>').appendTo('body')
            .html('<div><h6>'   message   '?</h6></div>')
            .dialog({
            modal: true,
            title: 'Delete message',
            zIndex: 10000,
            autoOpen: true,
            width: 'auto',
            resizable: false,
            buttons: {
                Yes: function() {
                    $(this).dialog("close");
                    return 'yes'
                },
                No: function() {
                    $(this).dialog("close");
                    return 'no'
                }
            },
            close: function(event, ui) {
                $(this).remove();
            }
        });
};

CodePudding user response:

You can pass another function to ConfirmDialog as a callback.

ConfirmDialog(msg, (response) => {
    if (response === 'yes') {
        // Do something here
    }
});

function ConfirmDialog(message, callback) {
    $('<div></div>').appendTo('body')
        .html('<div><h6>'   message   '?</h6></div>')
        .dialog({
        modal: true,
        title: 'Delete message',
        zIndex: 10000,
        autoOpen: true,
        width: 'auto',
        resizable: false,
        buttons: {
            Yes: function() {
                callback('yes');
                $(this).dialog("close");
            },
            No: function() {
                callback('no');
                $(this).dialog("close");
            }
        },
        close: function(event, ui) {
            $(this).remove();
        }
    });
};
  • Related