简体   繁体   中英

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.

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.

In addition to Thamilan's answer about the name attribute you should use empty ($POST['val1']) instead of isset . Here is a complete working example:

<!DOCTYPE html>
<head>
<?php
if (empty($_POST['val1'])) 
  print "<title>Not yet submitted</title>";
else 
{
  echo "<script>alert(".$_POST['val1'].")</script>";
  echo "<title>Submitted</title>";
}
?>
</head>
<body>
<?php
  echo "<form id='form_id' method='post' name='myform'>";
  echo "<input name='val1' id='val1' type='text' value='7'>";
  echo "<input id='submit' type='submit' value='submit'>";
  echo "</form>";
?>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM