Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate won't submit form with ajax check [duplicate]

I'm using the jQuery Validate plugin to validate an email field in my form by making an ajax request to make sure that the email is not already taken by another user. I do so by adding a rule like this:

//make sure email field is on form before adding rule
if ($(".unique_email").is("*")) {
    //remote validation
    $(".unique_email").rules("add", {
        remote: "http://test.nethop.com/test.cgi",
        messages: {
            remote: "This email is already in use"
        }
    });
}

However, whenever I hit 'submit' on the form, it will first do an ajax request to make sure the email isn't taken, and then it will not submit even if the email validates as okay. You have to hit submit one more time and then it will submit. Does anyone know why this is?

I've set up a jsfiddle demonstrating the problem. If you use chrome developer tools or firebug, you can see the ajax request being made, returning true, and still not submitting.

The HTML

<form id="listing" method="post">
    <ul>
        <li>
            <label for="username">Email *</label>
            <input type="text" name="username" id="username" autocomplete="off"
            class="email required unique_email" value="[email protected]" />
        </li>
        <li>
            <input type="submit" name="submit" id="submit" class="btn" value="Save"
            />
        </li>
    </ul>
</form>

The full script:

$(document).ready(function () {
    var validator = $("form").validate({
        onkeyup: false,
        onblur: true,
    });

    if ($(".unique_email").is("*")) {
        //remote validation
        $(".unique_email").rules("add", {
            remote: "http://test.nethop.com/test.cgi",
            messages: {
                remote: "This email is already in use"
            }
        });
    }
});
like image 631
srchulo Avatar asked Mar 12 '13 21:03

srchulo


1 Answers

Okay, this one is kind of weird so bear with me.

The fact that you have an input with name/id submit is causing the problem. I think this is because under the hood, jQuery validate is calling form.submit. In your case, form.submit is a form element and so this does nothing.

If you rename the submit button, everything works fine.

Example: http://jsfiddle.net/42TK4/7/

like image 90
Andrew Whitaker Avatar answered Nov 15 '22 07:11

Andrew Whitaker