Reputation: 25
here is my 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 the form
});
});
and my 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 is executed several times depend on which fields is filled. If I fill two fields will be executed 3 times if I fill 3 fields 4 times. This is not always the case but definitely my doPost method in the servlet is called several times .... I click on the submit button only once !!! Why ?
Upvotes: 0
Views: 254
Reputation: 1074108
Because every time the button is clicked, you're adding a further submit
handler to the form. Any time you find yourself hooking up an event handler from within another event handler, you want to think carefully if that's really want you want to do (usually, it isn't).
Hook submmit
outside the 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 the form
});
});
Upvotes: 2