How can I submit multiple forms with the same name? Please see my code below I’m unable to figure it out. I’m using PHP if I use dynamic PHP variable in the form name, then how can ajax will know that it was submitted. Any help would be highly appreciated.
<div>
<form method="post" id="formpressed" enctype="multipart/form-data">
<input type="text" name="question" id="question">
<input type="text" name="question2" id="question2">
<button class="btn-primary btn modalsubmit" name="save" id="save">Submit</button>
</form>
</div>
<div>
<form method="post" id="formpressed" enctype="multipart/form-data">
<input type="text" name="question" id="question">
<input type="text" name="question2" id="question2">
<button class="btn-primary btn modalsubmit" name="save" id="save">Submit</button>
</form>
<!-- FORM 3 -->
<!-- FORM 4 -->
<!-- FORM n -->
</div>
<script type="text/javascript">
$('#formpressed').on('submit', function(event){
event.preventDefault();
btnSubmit = $('.modalsubmit');
$.ajax({
url:'post.php',
method:"POST",
data: new FormData(this),
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
btnSubmit.prop('disabled', true);
},
success:function(data)
{
alert(data);
$("#formpressed")[0].reset();
}
});
});
</script>
2
Answers
In HTML
id
is an abbrevation for identity, and should be unique. To share an name betweenform
s use aclass
name, like:And in script use
$(this).find('.modalsubmit')
to find thesubmit
button inside yourclick
edform
, like:id must unique all html. so always use unique id for each html element.
better way is to use by form name or class name
you can get form using $(this)
to find the submit button inside form $(this).find(‘.modalsubmit’);
to get all form to be serialized you can do var formData = $(this).serialize();
$(‘form[name="formpressed"]’).on(‘submit’ work same as $(‘form[name="formpressed"]’).submit( but when you use $(document).on(‘submit’,’form[name="formpressed"]’ then it will also work for the DOM added later.
I have also added jsfiddle for this check here
https://jsfiddle.net/px95160o/