jQuery.validate plugin and ajax form submission

后端 未结 3 1401
谎友^
谎友^ 2021-01-03 01:34

I cannot for the life of me get this to work. The validation errors appear fine, I don\'t get syntax errors but nothing happens. The form just submits to the page. I can\'t

3条回答
  •  一整个雨季
    2021-01-03 02:36

    Just to help bring this post up-to-date.

    Encapsulate with:

    $(document).ready(function() { ALL YOUR CODE GOES HERE }
    

    Remove submitHandler from rules:

    rules: {
              name: {required: true},
              email: {required: true},
              subject: {requred: true}
          },
    submitHandler: function(form) {.....
    

    Add cache: false, to help prevent the browser form returning cached content:

    request = $.ajax({
        type: "POST",
        cache: false,
        url: "/contact/process.php",
        data: $(form).serialize(),
        timeout: 3000
    });
    

    Use done() and fail() instead of success and error now:

    // Called on success.
    request.done(function(msg) {
        alert('works');
    });
    // Called on failure.
    request.fail(function (jqXHR, textStatus, errorThrown){
        alert('failed');
        // log the error to the console
        console.error(
            "The following error occurred: " + textStatus, errorThrown
        );
    });
    

    Here's the whole thing:

    $(document).ready(function() {
        $("#contact").validate({
            rules: {
                name: {required: true},
                email: {required: true},
                subject: {requred: true}
            },
            submitHandler: function(form) {
                request = $.ajax({
                    type: "POST",
                    cache: false,
                    url: "/contact/process.php",
                    data: $(form).serialize(),
                    timeout: 3000
                });
                // Called on success.
                request.done(function(msg) {
                    alert('works');
                });
                // Called on failure.
                request.fail(function (jqXHR, textStatus, errorThrown){
                    alert('failed');
                    // log the error to the console
                    console.error(
                        "The following error occurred: " + textStatus, errorThrown
                    );
                });
                return false;
            }
        });
    });
    

    Add no-cache to process.php header to help prevent the browser form caching content:

    
    

提交回复
热议问题