简体   繁体   English

ajax提交和jQuery验证后,表单未刷新

[英]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. 我有一个要提交到数据库的表单,该表单包括要提交的Jquery Validate插件和ajax。

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. 我遇到的问题是,单击提交表单后无法清除,它会更新到数据库等,但是我只是想清除表单并在输入字段中突出显示CSS,以便有人可以添加新记录。 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: 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>则可以在reset()调用之后使用它:

$('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. 但是阅读您的评论后,我看到您将必须使ajax调用同步。 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 这就是您在process.php之前看到清晰表格的原因

In the ajax call pass async also in the object parameter- 在ajax调用中,还要在对象参数中传递async-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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