jquery-form/form

Submit only if a promise is resolved (beforeSubmit).

Leftyx opened this issue · 2 comments

Hello.
I would like to integrate http://bootboxjs.com/ as confirmation dialog before submitting my form (ajax).
I've tried to figure out how to implement something and came up with this solution.

When I create my options I add a callback (beforeSubmitPromise):

var options = {
    clearForm: false,
    data: {},
    // beforeSubmit: beforeSubmitting,
    beforeSubmitPromise: bootBoxConfirmPromise,
    success: function (result) {}
};
$('#formAbout').ajaxForm(options);

which calls a function which returns a promise:

function bootBoxConfirmPromise()
{
    var deferred = new jQuery.Deferred();

    bootbox.confirm("Are you sure you want to send this form ?", function (result) {
    if (result) {
        deferred.resolve(true);
    }
    else {
        deferred.reject(false);
    }
    });

    return deferred.promise();
}

and then I've changed the doAjaxSubmit function this way:

// private event handlers
function doAjaxSubmit(e) {
    /*jshint validthis:true */
    var options = e.data;
    if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
        e.preventDefault();

        if (options.beforeSubmitPromise) {
        $.when(options.beforeSubmitPromise()).then(
           function (status) {
               $(e.target).ajaxSubmit(options); // #365
           },
           function (reason) {
               log('ajaxSubmit: submit aborted via beforeSubmitPromise. reason: ' + reason);
           });
        }
        else {
        $(e.target).ajaxSubmit(options); // #365
        }
    }
}

It seems to work but I don't know if it can be implemented in a better and proper way.

Thanks.

I suspect it would require a pretty big reengineering in order to support promises properly. But I don't know, I have limited experience with implementing jQuery promises.

If anyone has any thoughts or suggestions (or pull requests), that would be helpful.

I am closing this issue due to a lack of activity. If you still need help, please comment and we can reopen.