3

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 results on the same page via jQuery. I don't want the form to do a default submit (and go to the servlet) because I want to stay on the same page and display results dynamically. It works exactly how I want it to as is:

HTML:

<form name="form1" action="FormHandler1" method="POST" class="stats-form">
    <input class="stats-input" id="number0" type="text" name="number0">
    <input id="number1" type="text" name="number1">
    <input id="number2" type="text" name="number2">
    <input id="number3" type="text" name="number3">
    <input type="submit" value="Calculate" class="calculate-stats" name="stats-submit">
</form>

jQuery:

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

Now, I wanted to add form validation, since the servlet expects decimal numbers to do it's calculations. The user should only be allowed to enter numbers, no other characters. To do this I adopted the popular jQuery Validation plugin.

The validation works as expected, but to make my ajax call to the servlet I have to use the submitHandler jQuery Validation provides, instead of the jQuery submit method shown above. When I use the validation submitHandler, the default action of the form on submit is executed, going to the servlet page instead of staying on the same page to display my results dynamically in jQuery. I have to pass the formHandler a form, instead of an event like before, which allowed me to prevent the default action. The only option is to return false, but it doesn't work. I've been trying to figure this out for the past two days, and have pretty much exhausted my google-fu. Here is the new code giving me grief:

form.validate({
       rules: {
            number0: ruleSet,
            number1: ruleSet,
            number2: ruleSet,
            number3: ruleSet,
        },
        submitHandler: function (form) {

            $.ajax({
                type: "POST",
                url: form.attr("action"),
                data: form.serialize(),
                success: function () {
                    // get response from servlet and display on page via jQuery 
                }
            });
            return false; // required to block normal submit ajax used
        }
 });

Any help would be appreciated, I'd like to use this neat jQuery form validation, but I may just write my own jQuery validation from scratch so that I can use the form submit method that I already have working.

5 Answers 5

8

By the time the submit event has fired it's too late to prevent the form from submitting. You should bind to the click event on the submit button and use event.preventDefault() to stop it from submitting. If your validation routine completes successfully you can use $.serialize() and $.submit() to manually submit the form.

1
  • Thank you, you helped me visualize the problem in a different way! I added my solution that works.
    – egl
    Oct 16, 2013 at 13:11
6

You can have event as the second parameter of submitHandler and can do preventDefault there itself.

submitHandler: function (form, event) {
    event.preventDefault();
    // your remaining code goes below this.
}
2

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
});
-1
$('#post_form_jason_data').click(function() {
$('#myform').validate({ 
    rules: {
        txtwtrt: {
            required: true
           // email: true
        },
        tax_name: {
            required: true,
            minlength: 5
        },
    tax_rate: {
            required: true
            //minlength: 5
        }
    }
});
alert('insert the value');
if (('#myform').valid()){


        $.ajax({
            url: "swt_tax_add.html",
            type: 'POST',
            data : $('#myform').serialize(),                
            success: function(msg) {
                window.location.href='swt_tax/?st=1';
                $('#message').html(msg);            

            }

        });
    }

        return false;
    });
1
  • Please add some context as to why you believe this solves the original problem Jul 22, 2014 at 11:50
-1

I know many people have answered but i'll show my entire code in 2020

$(document).ready(function () {
    $("#PaymentModeForm").validate({
        rules: {
            "f_cheque_mode_display": {
                required: true,
            },
            "f_cheque_infavour": {
                required: true,
            },
            "f_cheque_payablein": {
                required: true,
            },
            "f_cheque_address": {
                required: true,
            },
            "f_cheque_mobileno": {
                required: true,
            },
            "f_bank_mode_display": {
                required: true,
            },
            "f_bank_beneficiary": {
                required: true,
            },
            "f_bank_acc": {
                required: true,
            },
            "f_bank_bankname": {
                required: true,
            },
            "f_bank_branchname": {
                required: true,
            },
            "f_bank_ifsc": {
                required: true,
            },
            "f_cod_mode_display": {
                required: true,
            },
            "f_cod_mode_charges": {
                required: true,
            },
            "f_razorpay_mode_display": {
                required: true,
            },
            "f_razorpay_key": {
                required: true,
            },
            "f_razorpay_secret": {
                required: true,
            }
        },
        messages: {
            "f_cheque_mode_display": {
                required: "Enter Payment mode display on website"
            },
            "f_cheque_infavour": {
                required: "Enter Infavour Of",
            },
            "f_cheque_payablein": {
                required: "Enter Payble In",
            },
            "f_cheque_address": {
                required: "Enter Courier Address",
            },
            "f_cheque_mobileno": {
                required: "Enter Mobile No",
            },
            "f_bank_mode_display": {
                required: "Enter Payment mode display on website"
            },
            "f_bank_beneficiary": {
                required: "Enter Beneficiary Name",
            },
            "f_bank_acc": {
                required: "Enter A/C No",
            },
            "f_bank_bankname": {
                required: "Enter Bank Name",
            },
            "f_bank_branchname": {
                required: "Enter Branch Name",
            },
            "f_bank_ifsc": {
                required: "Enter IFSC Code",
            },
            "f_cod_mode_display": {
                required: "Enter Payment mode display on website",
            },
            "f_cod_mode_charges": {
                required: "Enter COD Charges",
            },
            "f_razorpay_mode_display": {
                required: "Enter Payment mode display on website",
            },
            "f_razorpay_key": {
                required: "Enter Key Id",
            },
            "f_razorpay_secret": {
                required: "Enter Secret Key",
            }
        },
        submitHandler: function (form, e) { 
            e.preventDefault();
            var form = $(this);
            var url = "/PaymentModeSubmit";
            $.ajax({
            type: "POST",
            url: url,
            data: $("#PaymentModeForm").serialize(),
            success: function(data)
            {
                alert(data);
            }
            });      
        return false;
        }
    });
    return
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.