Submitting a form using jQuery Ajax results in multiple requests (and submissions)

I ran into a problem with submitting a jQuery form and found no answers anywhere. If someone can shed light on this, he will be highly appreciated.

Problem: the first time I submit the form, it works fine. But , if I send the same form a second time, it sends 2 requests, 3 requests a third time, etc.

Script:

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

Dynamically generated form:

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

This is clearly undesirable. The only solution I can think of is an identifier to reprocess the (dynamically generated) form after submitting, but it will be an expensive operation.

Is this a known issue when introducing jQuery ajax or am I missing something obvious? Is there some form of recursion?

Thank.

+3
3

, , . $(formId).submit(...); . , , "". unbind . , $(formId).unbind('submit').submit(...);.

+6

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

submit. submit, function input type="submit". function submit. , , function submit, , functions.

, , :

$('#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>
+2

Edit

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

to

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

input type = "submit"> causes a double submission.

0
source

Source: https://habr.com/ru/post/1760108/


All Articles