AJAX and jQuery validate issue

大兔子大兔子 提交于 2019-12-02 19:14:49

问题


So I got stuck in this dead end. I have AJAX script and jQuery Validation plug-in. With this script, when my page loads empty contact form automatically submits on itself. If I move or add $('#submit').click(function () { over AJAX script part, right below $(document).ready(function() { then on submit it ignores my validation form.

Any help will be greatly appreciated.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js'></script>
<script>
    var captcha_a = Math.ceil(Math.random() * 10);
    var captcha_b = Math.ceil(Math.random() * 10);
    var captcha_c = captcha_a + captcha_b;

    function generate_captcha(id){
        var id = (id) ? id : 'lcaptcha';
        $("#"+id).html(captcha_a + " + " + captcha_b + " = ");
    }

    $(document).ready(function() {

        $('#submit').click(function () {

            jQuery.validator.addMethod("math",
                function(value, element, params) { return this.optional(element) || value == params[0] + params[1]; },
                jQuery.format("Please enter the correct value for {0} + {1}")
            );

            $("#commentform").validate({
                rules: {
                    captcha: {
                        math: [captcha_a, captcha_b]
                    }
                }
            });

        });

    })
</script>

<script>
    $(document).ready(function() {

        var name = $('input[name=name]');
        var phone = $('input[name=phone]');
        var email = $('input[name=email]');
        var reason = $('select[name=reason]');
        var info = $('textarea[name=info]');

        var data = 'name=' + name.val() + '&phone=' + phone.val() + '&email=' + email.val() +'&reason=' + reason.val() + '&info='  + encodeURIComponent(info.val());

        $('.loading').show();

        $.ajax({
            url: "ajaxformtoemail.php",
            type: "GET",
            data: data, 
            cache: false,
            success: function (html) {  
                if (html==1) {
                    $('.form').fadeOut('slow'); 
                    $('.done').fadeIn('slow');
                } else alert('Sorry, unexpected error. Please try again later.');
            }
         });
         return false;
    });
</script>

回答1:


Your ajax is running on page load because nothing is stopping it. You need to put the ajax code inside an event handler so it's only called if/when your form passes validation.

The following is an example of the proper implementation of the Validation Plugin. And you do not need to put the validate() inside a click handler. The Validation plugin has a bunch of its own handlers built in including a submitHandler that fires when the form passes validation.

<script type='text/javascript'>

$(document).ready(function() {

    jQuery.validator.addMethod("math",
        function(value, element, params) { return this.optional(element) || value == params[0] + params[1]; },
        jQuery.format("Please enter the correct value for {0} + {1}")
    );

    $('form').validate({
        rules {
            // your rules
        },
        submitHandler: function(form) {
            $.ajax({
                // your ajax parameters
            });         
            return false;
        }
    });

});

</script>

Validation Plugin Documentation

Some side issues...

  1. Your code would be much easier to read & troubleshoot if you used proper indentation and standard formatting.

  2. There is not need to use duplicate document.ready functions. Everything can be inside one.

  3. Like in #2, you do not need separate sets of <script></script> tags to contain your code. Everything can be enclosed once.



来源:https://stackoverflow.com/questions/9460831/ajax-and-jquery-validate-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!