不要允许多个表单提交

时间:2016-03-09 16:06:43

标签: javascript jquery forms unobtrusive-validation recaptcha

我正在尝试验证Google Captcha和我目前确实有效的表单。我正在使用JQuery Forms和Validate Unobstructive。问题是提交后,您仍然可以在单击时多次提交表单。

有没有办法确保只发生一次?

我已尝试使用以下内容(在代码中注释),但是您无法再次提交表单以重新检查验证码:

if ($form.data('submitted') === true) { } else { }

JS:

$(document).ready(function () { 
    //Intercept Submit button in order to make ajax call instead of a postback
    $('#contactForm').preventDoubleSubmission();
});

// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
    $("button").click('submit', function (e) {
        e.preventDefault();

        var $form = $("#contactForm");

        $($form).bind("invalid-form.validate", function() {
            if( $("invalid-form.validate") ) {
                formErrors();
            }
        })

        // if ($form.data('submitted') === true) {
            // // Previously submitted - don't submit again
        // } else {
            if ($form.valid()) {
                // Mark it so that the next submit can be ignored
                $form.data('submitted', true);
                if ( captchaCheck() == false) {
                    captchaCheck();
                } else {
                    // Make ajax call form submission
                    $.ajax({
                        url: $form.attr('action'),
                        type: 'POST',
                        cache: false,
                        data: $form.serialize(),
                        success: function (result) {
                            success();
                        }
                    });
                }   
            }
        // }        
    });

    // keep chainability
    return this;
};

function hover() {
  $(".contour-button").on("mouseenter", function() {
    return $(this).addClass("hover");
  });
}

function hoverOff() {
  $(".contour-button").on("mouseleave", function() {
    return $(this).removeClass("hover");
  });
}

function success() {
    $(".contour-button").addClass("success");
    var formFields = $(".contactForm input, .contactForm textarea, .contactForm button");
    $(formFields).attr('disabled', 'disabled');
    $(formFields).animate({'opacity':'0.5'});
    $(".contour-btn-arrow").addClass("contour-btn-success");
    $(".contour-button .submit").html("Thank you for your enquiry");
}

function formErrors() {
    $(".contour-button").addClass("form-errors").delay(3500).queue(function(){
        $(this).removeClass("form-errors").dequeue();
    });
    $(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
        $(this).removeClass("contour-btn-error").dequeue();
    });
    $(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
        $(this).html("Submit").dequeue();
    });
}

function captchaCheck() {
    var captchaResponse = grecaptcha.getResponse();
    if(captchaResponse.length == 0) {
        // html for the captcha error message
        var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';

        $("#captchaMsg").html(captchaMsgHtml).slideDown(500);
        $(".g-recaptcha div div").addClass("recaptchaHighlight");
        return false;
    } else {
        $(".g-recaptcha div div").removeClass("recaptchaHighlight")
        $("#captchaMsg").hide();
        return true;
    }
}

hover();
hoverOff();

3 个答案:

答案 0 :(得分:2)

您可以暂停点击按钮

var that = this;
$(that).attr("disabled", true);

e.preventDefault();

然后,如果需要,在使用

完成操作时启用它
//probably after success()
$(that).attr("disabled", false);

我希望这就是你所需要的!

答案 1 :(得分:0)

首先,如果您实际使用<form>专用<submit><button type="submit">Submit</button>,那么您应该正在倾听on.('submit')

var allowSubmit = TRUE;

$('form').on('submit', function(e)
{
    if(allowSubmit === TRUE)
    {
        allowSubmit = FALSE;

        // Perform your validations + AJAX calls and make sure to set
        // allowSubmit = TRUE; wherever appropriate

        if(validationFails)
        {
            allowSubmit = TRUE;
        }
        else
        {
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                cache: false,
                data: $form.serialize(),
                success: function (result) {
                    success();
                    allowSubmit = TRUE;
                },
                error: function() {
                    // Do some error handling

                    allowSubmit = TRUE;
                }
            });
        }
    }
    else
    {
        e.preventDefault();
    }
});

答案 2 :(得分:0)

我设法通过使用bool(true / false)将AJAX调用包装在一个条件中,以类似于MonkeyZeus的建议来解决这个问题。

var ajaxRunning = false;

$("button").click('submit', function (e) {
    e.preventDefault();

    var $form = $("#contactForm");

    $($form).bind("invalid-form.validate", function() {
        if( $("invalid-form.validate") ) {
            formErrors();
        }
    })

    if ($form.valid()) {
        if ( captchaCheck() === false) {
            captchaCheck();
            formErrors();
        } else {
            if(!ajaxRunning){
            ajaxRunning = true;
                $.ajax({
                    url: $form.attr('action'),
                    type: 'POST',
                    cache: false,
                    data: $form.serialize(),
                    success: function (result) {
                        success();
                    },
                    error: function (result) {
                        captchaCheck();
                        formErrors();
                    }
                });
            }
        }   
    }       
});

function hover() {
  $(".contour-button").on("mouseenter", function() {
    return $(this).addClass("hover");
  });
}

function hoverOff() {
  $(".contour-button").on("mouseleave", function() {
    return $(this).removeClass("hover");
  });
}

function success() {
    var disabledElements = "#formFooter button, .contourField input, .contourField textarea";
    var opacityElements = ".contourField input, .contourField textarea";

    // disable button & inputs once submitted
    $(disabledElements).attr('disabled', 'disabled');

    // change opacity of elements
    $(opacityElements).animate({ 'opacity' : '0.5' });

    $(".contour-button").addClass("success");
    $(".contour-btn-arrow").addClass("contour-btn-success");
    $(".contour-button .submit").html("Thank you for your enquiry");
}

function formErrors() {
    $(".contour-button").addClass("form-errors").delay(3500).queue(function(){
        $(this).removeClass("form-errors").dequeue();
    });
    $(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
        $(this).removeClass("contour-btn-error").dequeue();
    });
    $(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
        $(this).html("Submit").dequeue();
    });
}

function captchaCheck() {
    var captchaResponse = grecaptcha.getResponse();
    if(captchaResponse.length == 0) {
        // html for the captcha error message
        var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';

        $("#captchaMsg").html(captchaMsgHtml).slideDown(500);
        $(".g-recaptcha div div").addClass("recaptchaHighlight");
        return false;
    } else {
        $(".g-recaptcha div div").removeClass("recaptchaHighlight")
        $("#captchaMsg").hide();
        return true;
    }
}

hover();
hoverOff();