Search code examples
jqueryrecursionbootstrapvalidator

jquery too much recursion error on form.each function with bootstrap validation


There was no console error for my form that uses Bootstrap Validator (http://formvalidation.io/) until I needed to put multiple forms on the page. Now, when I run $(form).each(), I'm getting a too much recursion error.

    $('form').each(function(){
        var form_id = $(this).attr("id");
        $(this).bootstrapValidator({
            message: 'This value is not valid',
            fields: {
                email: {
                    validators: {
                        notEmpty: {
                            message: 'The email is required and cannot be empty'
                        },
                        emailAddress: {
                            message: 'The input is not a valid email address'
                        }
                    }
                }                   
            }
        }).on('success.form.bv', app.form_handler);
    });

Here's the javascript app.form_handler:

app.form_handler = function( evt ){
    evt.preventDefault();
    app.$ajax_form = $(evt.target);
    var serialized_data = app.$ajax_form.serialize();
    app.post_ajax( serialized_data );
};

Then the post_ajax function...

 app.post_ajax = function( serial_data ){
    var post_data = { 
        action     : 'cm_ajax',
        nonce      : cm_ajax.nonce,
        serialized : serial_data,
    };

    $.post( cm_ajax.ajax_url, post_data, app.ajax_response, 'json' )
};

Solution

  • The Too Much Recursion Error issue might happen if there is a form that doesn't follow Bootstrap form structure. See the Writing form section.

    Meanwhile, $(form) actually will choose ALL forms in the page. So, either checking ALL forms on page to ensure that ALL of them use a standard Bootstrap form markup, or uses more strict selector such as $('#form1, #form2')