PHP $ _POST variable does not process input fields created by Javascript

I have two files (file1 and file2). file1 includes file2 in the PHP include statement. File1 also contains the form and displays all the $ _POST variables. File2 uses the Javascript button to dynamically change the value in the input field. The problem is that $ _POST is empty after clicking submit. Why is this and how to fix it?

File1:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php include 'file2.php'; ?> 
<input type="submit" /></form>

<?php foreach ($_POST as $key => $val) { echo $key . " belongs to " . $val; } ?>

File2

<script type="text/javascript">
        var button = {
        counter : 0,

            count : function() {
            text = document.getElementById("text");
            this.counter++;
            text.setAttribute("value", this.counter);
        }
    };
    </script>

<button type="button" onclick="button.count()">CLICK ME!</button>
<input id="text" type="text" value="0" />
+3
source share
3 answers

You forgot to set the attribute name:

<input id="text" name="text" type="text" value="0" />
+5
source
text.setAttribute("value", this.counter);

This is better than:

text.value = this.counter;

You also need the name attribute for your element:

<input id="text" name="text" type="text" value="0" />
+2
source

You have not set the name attribute for the text field.

Corrected Code:

<input id="text" name="text" type="text" value="0" >
0
source

All Articles