0

I wanted to make an ajax call, and then wait for the response from ajax call (Stop form submission till then) and then post the form based on the ajax response that I get. This question is based on Make ajax call and then submit form. So, after putting below script, everything works fine, but I lose the client side validation. Can I make an ajax call and still respect the Client Side validation?

@section scripts {
    <script>
        var canSubmit = false;
        $('form').submit(function (e) {
            if (!canSubmit) {
                e.preventDefault();
                var data = $('form').serialize();
                var url = $(this).data('url');
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    success: function (response) {
                        if (response.hasPreviousRequest) {
                            if (confirm("You've already applied for this job. Apply again?")) {
                                canSubmit = true;
                                $('form').submit();
                            }
                        }
                        else {
                            canSubmit = true;
                            $('form').submit();
                        }
                    },
                    error: function () {
                        alert("error");
                    }
                });
            }
        });
    </script>
}

P.S: Kindly note that as soon I as remove the ajax call Client side validation starts working fine. Can some one please explain me this behaviour?

Unbreakable
  • 7,776
  • 24
  • 90
  • 171

1 Answers1

2

You need to call the .valid() method on the form element (and if not, then cancel the ajax call)

$('form').submit(function (e) {
    if (!$(this).valid()) {
        return // exit
    }
    if (!canSubmit) {
        ....