I am trying to submit multiple forms seperatly one by one with one button click. I populate my input forms with the SQL variable $name
and id="form<?= $i ?>"
depending on the result the creates the id form1,form2 etc. I then need to send all of these forms with one click. but seperetly from each other, so first the form with id form1 than form2 etc.
The problem. The way I have it now only submits one of the forms the last one that is generated. What am I doing wrong? The consol is not giving any errors and all the forms are generated with the correct Ids (form1,form2,form3 etc..)
PS: I cannot use ajax Xmlrequest for this matter.
$type = "test"
$i=0;
$stmt = $mysqli->prepare("SELECT name FROM account WHERE purpose = ? ");
$stmt->bind_param('s',$type);
$stmt->execute();
$result = $stmt->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result->fetch_assoc())
{
$name = $rowid['name'];
$i++
?> <form method="post" id="form<?= $i ?>" target="_external" action="https://www.externalwebsite.com/index/post.php">
<input type="hidden" value="<?= $name ?>" name="sendname" >
</form>
<?PHP } ?>
<button id="submit">Submit</button>
<script>
document.getElementById( 'submit' ).addEventListener( 'click', function () {
// check for and report errors here
for( var index = 0; index < document.forms.length; index++ ) {
document.forms[index].submit();
};
} );
</script>
My Answer:
Here is an example of how you can achieve this using PHP and JavaScript:
1. Create multiple forms with unique IDs and a submit button inside each form:
php
// Assuming $names is an array of names fetched from SQL
foreach ($names as $name) {
echo "";
}
?>
2. Add a single button that will trigger the submission of each form one by one:
html
3. Use JavaScript to submit each form sequentially when the button is clicked:
javascript
document.getElementById('submitAllForms').addEventListener('click', function() {
var forms = document.querySelectorAll('form');
var index = 0;
function submitForm() {
if (index < forms.length) {
forms[index].submit();
index++;
}
}
submitForm();
});
4. Handle the form submission in your PHP script (submit.php) by accessing the submitted data:
php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
// Process the form data as needed
}
?>
With this setup, when the "Submit All Forms" button is clicked, each form will be submitted one by one, and the data from each form will be processed in the submit.php script.
Rate this post
4 of 5 based on 5928 votesComments