jquery - Why Ajax post request is executed several times? -


here code:

$(document).ready(function(){             $("#mainbutton").click(function(){                 $("#ajaxform").submit(function(e){                     var info = $(this).serialize();                     $.ajax(                     {                         url : "userctrl",                         type: "post",                         data : info,                         success:function(data, textstatus, jqxhr)                          {                             console.log("success");                              $('.valid-error').html(data);                         },                     });                     e.preventdefault()                 });                 $("#ajaxform").submit(); //submit form             });         }); 

and html

        <form id="ajaxform">         <input type="hidden" name="action" value="submit"/>         <input type="text" placeholder="name" name="name" id="name" /><span></span>         <input type="text" placeholder="surname" name="surname" /><span></span>         <input type="text" placeholder="address" name="address" /><span></span>         <p class="valid-error"></p>         <input id="mainbutton" class="mainbutton" type="button" value="trial"/>         </form> 

this request executed several times depend on fields filled. if fill 2 fields executed 3 times if fill 3 fields 4 times. not case dopost method in servlet called several times .... click on submit button once !!! why ?

because every time button clicked, you're adding further submit handler form. time find hooking event handler within event handler, want think if that's want want (usually, isn't).

hook submmit outside click handler:

$(document).ready(function() {     $("#ajaxform").submit(function(e) {         var info = $(this).serialize();         $.ajax({             url: "userctrl",             type: "post",             data: info,             success: function(data, textstatus, jqxhr) {                 console.log("success");                 $('.valid-error').html(data);             },         });         e.preventdefault()     });     $("#mainbutton").click(function() {         $("#ajaxform").submit(); //submit form     }); }); 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -