简体   繁体   中英

form is not refreshing after ajax submit and jquery validate

I have a form which I am submitting to my database, the form includes Jquery Validate plugin and ajax to submit.

The issue I am having is that after I click submit the form does not clear, it updates to database etc but I am just trying to clear the form and css highlight on the input field so someone could add a new record. Any help please?

CODE:

$(document).ready(function () {
    $.validator.addMethod("time", function (value, element) {
        return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
    }, "Please enter a valid time.");

    $("#newform").validate({

        //validation
        debug: false,
        rules: {
            Name: {
                required: true,
                minlength: 3,
            },

            Surname: {
                required: true,
            },

        },

        submitHandler: function (form) {
            $.post('process.php', $("#newform").serialize(), function (data) {
                $('#results').html(data);
                $('#newform').reset();
            });
        }
    });
});

HTML:

<form name="newform" id="newform" action="" method="POST">  



    <p>Name:</p>
        <input type="text" id="pName" name="sName" /><br />

    <p>Surname:</p>
        <input type="date" id="pSName" name="pSName" /><br />


    <input type="submit" name="submit" value="Submit"> 
</form>

<div id="results"><div>

You can use the following code to clear your form:

$('#newform').reset();

To focus on a specific <input> then you can use this after the reset() call:

$('input[name="sName"]').focus();

Try the following:

submitHandler: function (form) {
    var jqxhr = $.post('process.php', $("#newform").serialize(), function (data) {
        $('#results').html(data);
    });

    jqxhr.done(function() {
        $('#newform')[0].reset();
    });
}
$('#newform').reset();

The above code will do. But reading your comments I see that you will have to make the ajax call synchronous. Because if its asynchronous, you will clear the form before the submit request is actually processed on server side. That's the reason you see a clear form before process.php

In the ajax call pass async also in the object parameter-

{url:'xyz.com',async:false}

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