1

I have created a php form which appends new text variables like this:

<form action="" enctype=”multipart/form-data” method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>">

    <div id="div">
        value <input type="text" name="tst" >
     <button onclick ="appendRow()" value="Add Row">Add Row</button>
     <input type="submit" value="test" name="submit" >
     </div>
</form>

I have added the following java script to it:

<script> 
    var x=1
function appendRow()
{
   var d = document.getElementById('div');
   d.innerHTML += "<input type='text' name='tst"+ x++ +"'><br >";
}
</script>

Now I want to store all the variables I get from the form and use them for further calculations. I tried the for each loop for that:

if (isset($_POST['submit']) && is_array($_POST['submit'] == "test")) {
    foreach($_POST["submit"] as $key => $tst){
        $capture_field_vals .= $tst .", ";
    }
    echo $capture_field_vals;

But nothing is happening. Can you please tell me what is wrong ?

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
Rachel Watson
  • 212
  • 2
  • 9

2 Answers2

2

First, remove the action properties from your form.

<form enctype="multipart/form-data" method="post">
    ...
</form>

Having multiple form actions is not supported, and forms will post to the same page they were submitted to if no action is given (by default).

Next, submit your form name='tst' as an array, like this:

<input type="text" name="tst[]"/>

And in you JavaScript, do the same:

d.innerHTML += '<input type="text" name="tst[]"/><br>';

(You do not need the x variable), (input arrays)

Now, in your PHP you can loop through all of the submitted tst values.

if (isset($_POST['submit'])) {
    foreach($_POST['tst'] as $tst){
        $capture_field_vals .= $tst .", ";
    }
    echo rtrim($capture_field_vals, ','); //rtrim will remove trailing comma
}

(rtrim() documentation)

But this can be simplified even more with implode().

if(isset($_POST['submit'])) {
    echo implode(', ', $_POST['tst']);
}
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
0

Your loop seems wrong. There's nothing to loop through with $_POST['submit'], it's just a single value. The actual array is $_POST.

foreach($_POST["submit"] as $key => $tst){
        $capture_field_vals .= $tst .", ";
    }

Try this:

foreach($_POST as $key => $tst){
        $capture_field_vals .= $tst .", ";
    }
Difster
  • 3,264
  • 2
  • 22
  • 32