简体   繁体   English

jQuery验证在Ajax表单提交中不起作用

[英]jQuery validation not work in Ajax Form Submit

I submit my form using jQuery $.post method and need to validation form using jQuery validation plugin like this : 我使用jQuery $.post方法提交表单,并且需要使用jQuery验证插件来验证表单,如下所示:

HTML : HTML:

<form name="myform" id="myform" action="send.php">User:
    <input type="text" value="" name="user" />
    <br/>Password:
    <input type="password" name="password" value="" />
    <input type="hidden" name="xyz" value="123" />
    <input type="hidden" name="submit" value="true" />
    <?php $token=N oCSRF::generate( 'csrf_token' );?>
    <input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
</form>
<button class="btn btn-info" id="ajax-form-1">Run Code</button>
<div id="ajax-form-msg1"></div>

JS: JS:

$('#myform').validate({

    rules: {
        user: {
            required: true
        },
        password: {
            required: true
        }
    },

    submitHandler: function (form) {
        $("#ajax-form-1").click(function () {
            $("#ajax-form-msg1").html("<img src='loading.gif'/>");

            //  var formData = $("#myform").serialize();  //or
            var formData = $("#myform").serializeArray();

            var URL = $("#myform").attr('action');
            $.post(URL,
            formData,

            function (data, textStatus, jqXHR) {
                $("#ajax-form-msg1").html('<pre><code class="prettyprint">' + data + '</code></pre>');

            }).fail(function (jqXHR, textStatus, errorThrown) {
                $("#ajax-form-msg1").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
            });

        });
    }
});

In action, jQuery validation not work with my form. 实际上,jQuery验证不适用于我的表单。 how do fix this ? 如何解决这个问题?

DEMO : http://jsfiddle.net/fcuswvf1/2/ 演示: http : //jsfiddle.net/fcuswvf1/2/

You are binding the click handler on the button inside the submitHandler . 您将单击处理程序绑定到submitHandler内的submitHandler This way, when a user clicks the button, the click event doesn't fire. 这样,当用户单击按钮时,不会触发click事件。 You can simply remove the click handling lines from the 'submitHandler , so that the code inside is called directly whenever submitHandler` is triggered. 您可以简单地从'submitHandler'中删除点击处理行, so that the code inside is called directly whenever触发SubmitHandler`时, so that the code inside is called directly whenever

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

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