Search code examples
phphtmlformssubmitposting

Form does not submit with php echo


I have the following code:

index.php

<?php
  if (isset($_POST['post'])) {
    echo "<script>alert(".$_POST['val1'].")</script>";
  }
?>

<html>
...
<body>
...
<?php
  echo "<form id='form_id' method='post' name='myform'>";
  echo "<input id='val1' type='text' value='7'>";
  echo "<input id='submit' type='submit' value='submit'>";
  echo "</form>";
?>
...
<body>
</html>

This will create a form, a text field and a submit button. All those shown perfectly fine except it would not submit the form. So my question is why does my form not work here and what should I do to solve this problem without moving it out from php.


Solution

  • Problem is that you are missing name attributes for the elements:

    <?php
      if (isset($_POST['post'])) {
        echo "<script>alert(".$_POST['val1'].")</script>";
      }
    ?>
    
    <html>
    ...
    <body>
    ...
    <?php
      echo "<form id='form_id' method='post' name='myform'>";
      echo "<input id='val1' name='val1' type='text' value='7'>";
      echo "<input id='submit' name='post' type='submit' value='submit'>";
      echo "</form>";
    ?>
    ...
    <body>
    </html>
    

    You can notice the addition of name attribute for text field and submit button. Only name attribute will be used to identify the fields when form gets posted.