Search code examples
phpbuttonsubmitpageload

Why is submit button set to true on page load?


I am trying to understand why this example form is acting though the submit button is set to true when the page initially loads. This is an example, but the underlying problem is that I am trying to do something when the submit button is click, but when the page loads, the code runs as though the button has already been clicked.

<?php
   $GLOBALS["zipcode"] = null;
?>

<!--========================Dialogue Box========================-->

<h2 class="ind3">Service Area</h2>

<form name="zipcodeform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   <p>Enter your zip code:</p>
   Zip:
   <label><input type="text" name="zipcode" value=""></label>
   <p /><p />
   <input type="submit" name="submit" value="Submit">

</form>

<?php
   /*Test to see if form submit button has been pressed. */
   If (isset($_POST['submit'])) {echo "the button has been pressed!";}
?>

<!--========================Dialogue Box========================-->

I know this is something simple, but I've spent hours googling and trying to figure out what I'm doing wrong. I want the PHP code at the end of the dialogue box to only display if the button is pressed, not automatically when the page loads. Thanks for your help!


Solution

  • It looks like you are trying to run server side code for a client-side action.

    PHP will always execute before the page loads. If you want to capture a user's action on the button, you will need to use JavaScript to handle the click event or the submit event.

    See the difference between server side and client side coding.