Why does my jquery ajax form submit once on first

2020-02-29 05:10发布

I have a simple AJAX form that works as it should when I submit it. However, if I then enter new data into the same form (without refreshing the page), then it submits the form twice. If I do this a third time, then it submits the form three time, and so on. Why is it doing this? Here is my code:

$(document).ready(function(){
    $("#myForm").submit(function() {
        var myField = $('#myID).val();
        $.ajax({
            type: "POST",
            url: 'myFile.php',
            dataType: 'html',
            data: {myData:myField},
            success: function(data){
                alert(data);
            }
        });

        return false;
    });
});

标签: ajax jquery
3条回答
叼着烟拽天下
2楼-- · 2020-02-29 05:41

Even I got stuck with the same problem while developing a AJAX login form. After an googling for couple of hours I found a solution. I hope this should help you out.

Basically you have to unbind the current instance of form's submit action after your ajax request gets completed. So add this line before return false;

$("#myform").unbind('submit');

Therefore your entire code should look like



    $(document).ready(function(){
        $("#myForm").submit(function() {
            var myField = $('#myID).val();
            $.ajax({
                type: "POST",
                url: 'myFile.php',
                dataType: 'html',
                data: {myData:myField},
                success: function(data){
                    alert(data);
                }
            });

            /* Add this line */
            $("#myform").unbind('submit');
            return false;
        });
    });


查看更多
手持菜刀,她持情操
3楼-- · 2020-02-29 05:50

Unbinding the form can break you Ajax from. I found that as long as I declare the form first.

$('#my_form').ajaxForm

that all works as expected, and follows the standard protocol. I just spent a day chasing the 'missing template' error on the form submission because I unbound the form.

查看更多
祖国的老花朵
4楼-- · 2020-02-29 05:52

I had the same problem.

I found the solution in: jquery : submitting a form twice

Basicaly is adding .submit() to Saurabh Mishra answer:

$('#form1').unbind('submit').submit();
查看更多
登录 后发表回答