javascriptjquery-toolsjquery-inputmask

Wait pending requests before finalize submit on Javascript


I have the following situation on a web application (javascript-jQuery):

When the form is submitted, sometimes, when the bank account is empty, the validation "required" is not checked. After a crazy debug, I've seen that the input mask control, is firing a change event, and so, the request is throwed to the server (so the input is disabled), and the validator doesn't validates the required, because it has a condition that the disabled fields are not validated.

I would to "pause" the validation until all requests are finished, but I haven't found the way to do it outside the library. Any idea of how to solve this problem wihtout modifying the external libs ("jquery inputmask" and "jquery tools")?


Solution

  • Finally I've choosed the following solution:

    When the submit button is pressed, check if there are pending requests before submitting. I use a javascript interval to check every 200ms (and during a max of 10 intervals to avoid unsubmitted forms by erroneous tracking).

    On the other hand, I check if the form is submitting before send a rule request on the server. If the form is submitting, I don't calculate the rule.

    I post the code adapted to understand.

    Function to check the form submit:

    // Check the form submit
    $(".submitButtom", ctl).click(function (e) {
        var $form = $(this).closest('form');
        var areServerRulesRunning = $.mpm.formengine.genericRules.runningServerRules > 0;
        if (areServerRulesRunning) {
            // If are server rules running keep checking before submit
            var retries = 10;
            var interval = setInterval(function() {
                if ($.mpm.formengine.genericRules.runningServerRules <= 0 || retries < 0) {
                    clearInterval(interval);
                    // variable to track the submission of the form
                    $.mpm.formengine.form.submitting = true;
                    $form.submit();
                }
                retries--;
            }, 200);
        }
        else {
            $form.submit();
        }
    });
    // Later on a callback after submit (don't published): $.mpm.formengine.form.submitting = false;
    

    Function that executes server rules on input changes:

    ...
    // Rule execution
    serverCalculationRule: function (wfName, $sourceInput, controlScope, ruleData) {
    
        if ($.mpm.formengine.form.submitting === true) {
            // If the form is submitting don't send the request to the server
            return;
        }
    
        $.mpm.formengine.genericRules.runningServerRules++;
        $.post($.mpm.Constants.FormEngine.UrlDoAction, doActionData,
            function (data) {
                // SUCCESS
            }
        )
        .always(function () {
            // ALWAYS
            $.mpm.formengine.genericRules.runningServerRules--;
    
        });
    },
    ...