jQuery Validation plugin: submitHandler not preventing default on submit when making ajax call to servlet - return false not working

前端 未结 5 1258
渐次进展
渐次进展 2021-01-14 06:35

I have a simple form that uses jquery and a servlet. The jquery makes an ajax call to the servlet, the servlet makes some server side calculations, then displays the result

5条回答
  •  悲哀的现实
    2021-01-14 07:38

    To resolve the problem, I validate the form separately my form submit handler. I simply put a check for validity inside the form submit, executing the ajax call only if true. This allows the action of the submit event to be handled (preventDefault()) regardless if the ajax call is made or not.

    form.validate({
        rules: {
            number0: ruleSet,
            number1: ruleSet,
            number2: ruleSet,
            number3: ruleSet,
        }
    });
    
    form.submit (function(event) {
        if (form.valid())
        {
            $.ajax({
                type: form.attr("method"), // use method specified in form attributes
                url: form.attr("action"), // use action specified in form attributes
                data: form.serialize(), // encodes set of form elements as string for submission
                success: function(data) {
                    // get response from servlet and display on page via jQuery 
                }
            });
        }
        event.preventDefault(); // stop form from redirecting to java servlet page
    });
    

提交回复
热议问题