skip to Main Content

Forgive me if I use incorrect terminology, or if this seems like a silly question. I’d appreciate any help.

I have a simple webpage, with php code that is suppose to execute when you press a button.

<!DOCTYPE html>

<head>
</head>

<body>

<?Php
echo "<form method=post action='script.php'>";
?>

<div>
<button>Click me</button>
</div>

</body>

The ‘script.php’ looks like this. Just a simple page that prints "Hello" statement.

<html>

<body>
<p> Hello </p>
</body>

</html>

But how does the <button> element placed after the php script know to do. How are they attached together?

action='script.php'

I noticed I that I could place a hundred buttons, and they all will execute the form. If fact, any button I place after the php script will behave the same.

<button>Button</button>
<button>Button</button>
<button>Button</button>

But why? What am I missing?

I tried looking online and on stack overflow but I wasn’t even sure what question to ask or what to search for.

2

Answers


  1. Add closing tag </form>

    When button is inside <form> tag.

    <button type="submit">Click me</button>
    

    While when button is outside <form> tag, assign id in form tag

    <form id="formID">
    <button type="submit" form="formID">Click me</button>
    
    Login or Signup to reply.
  2. This is due to the activation behavior of the button element itself.

    By default, if the type attribute is not specified, or if it is set to submit, then the default action of the button is to submit the form that it is contained within. When the button is clicked, the browser will send a request to the server with the data from all the form fields, using the method specified in the method attribute of the form element, which is post in your PHP.

    Check out the official documentation here. Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search