Submitting a form with JQuery Ajax results in multiple requests (and submissions)

爱⌒轻易说出口 提交于 2019-12-03 08:53:22
Paul Hadfield

Each time you click the button, the code is calling your function. In that function the line $(formId).submit(...); is binding the event to the form's submit action. This happens every time you click, adding multiple "submit" events to the form. You need to unbind the action first. So you could call $(formId).unbind('submit').submit(...); instead.

When you do this

$(formId).submit(function(){})

You are adding the function to the submit event. When you click in the submit button you are adding a this function and submitting through the default behavior of input type="submit". When you click again you add the same function to the submit event. So when you click one time you have one function in the submit event, when you click two times you have two functions.

That said you can do what you want like this:

$('#inputInvokeId').submit(function(){
var formUrl = "invokeFunction.html?functionId="+inputInvokeId;
$.ajax({
                type: 'POST',
                url: formUrl,
                data: $(formId).serialize(),
                success: function (data){
                 alert('successfully invoked function!' + data);
                }
            });
            return false;
           }

})

<form action="" method="post" id="xxxxx-form" class="invokeFunctionForm">
<input name="functionId" value="xxxxx" readonly="readonly" style="visibility: hidden;" type="text">
<input value="Invoke" id="inputInvokeId" type="submit">
</form>

Change

<input value="Invoke" onclick="postInvokeFunctionForm(xxxxx);" type="submit">

to

<input value="Invoke" onclick="postInvokeFunctionForm(xxxxx);" type="button">

The < input type="submit" > is what is causing the double submit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!