Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same page processing

How can process a form on the same page vs using a separate process page. Right now for signups, comment submissions, etc I use a second page that verifies data and then submits and routes back to home.php. How can I make it so that on submit, the page itself verifies rather than using a second page.

like image 480
AAA Avatar asked Jan 24 '11 14:01

AAA


2 Answers

You can tell the form to submit to the PHP's self, then check the $_POST variables for form processing. This method is very good for error checking as you can set an error and then have the form reload with any information the user's previously submitted still in tact (i.e. they don't lose their submission).

When the "submit" button is clicked, it will POST the information to the same page, running the PHP code at the top. If an error occurs (based on your checks), the form will reload for the user with the errors displayed and any information the user supplied still in the fields. If an error doesn't occur, you will display a confirmation page instead of the form.

<?php
//Form submitted
if(isset($_POST['submit'])) {
  //Error checking
  if(!$_POST['yourname']) {
    $error['yourname'] = "<p>Please supply your name.</p>\n";
  }
  if(!$_POST['address']) {
    $error['address'] = "<p>Please supply your address.</p>\n";
  }

  //No errors, process
  if(!is_array($error)) {
    //Process your form

    //Display confirmation page
    echo "<p>Thank you for your submission.</p>\n";

    //Require or include any page footer you might have
    //here as well so the style of your page isn't broken.
    //Then exit the script.
    exit;
  }
}
?>

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
  <?=$error['yourname']?>
  <p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
  <?=$error['address']?>
  <p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
  <p><input type="submit" name="submit" value="Submit" /></p>
</form>
like image 66
Michael Irigoyen Avatar answered Oct 14 '22 12:10

Michael Irigoyen


The easiest construction is to detect whether the $_POST array is not empty

if(isset($_POST['myVarInTheForm'])) {
  // Process the form
}

// do the regular job
like image 20
Jonas Schmid Avatar answered Oct 14 '22 11:10

Jonas Schmid