简体   繁体   中英

How to prevent form submit?

I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.

This my javascript Function:

$(document).ready(function () {
$("#signupform").submit(function (event) {        
    var captchacode = $("#captchatexbox").val();
    if (captchacode != "") {
        var url = "/Account/ValidateCaptcha?Code=" + captchacode;
        $.ajax({
            url: url,
            cache: false,
            success: function (data) {
                if (data == 0) {

                    alert("Invalid captcha");
                    event.preventDefault();
                    //Form post data still sent?
                }
            }
        });
    }
    else alert("Captcha not null");
   });
});

You need to move event.preventDefault(); up so it comes before the ajax call.

Use $("#signupform").submit(); in an else block to programmatically submit the form.

$(document).ready(function () {
$("#signupform").submit(function (event) {        
    event.preventDefault();
    var captchacode = $("#captchatexbox").val();
    if (captchacode != "") {
        var url = "/Account/ValidateCaptcha?Code=" + captchacode;
        $.ajax({
            url: url,
            cache: false,
            success: function (data) {
                if (data == 0) {
                    alert("Invalid captcha");
                    //Form post data still sent?
                } else {
                    $("#signupform").submit();
                }
            }
        });
    }
    else alert("Captcha not null");
   });
});

You would need have the form event.preventDefault(); before making the ajax request.

$("#signupform").submit(function (event) { event.preventDefault();

When the ajax request is returned, you can submit the form using:

if (data != 0) { $("#signupform").submit(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM