Thursday, June 28, 2012

PHP: Playing with a simple form

I was trying to come up with a solution to minimise the number of php files needed to manipulate and submit the form data and this is the solution that I have come up with. :D (Though it can be done using 3 php files but too many files lah...)

form.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<?
 $hasPostData = "false";
 $name = "";
 $address = "";
 $info = "";
 //Check if this php file has receive any form data
 //through POST method.
 if(isset($_POST["form_name"]))
 {
  $hasPostData = "true";
  $name = $_POST["form_name"];
  $address = $_POST["form_address"];
  $info = $name.$address;
 }
?>
</head>
<body>
<form action="" method="post" name="loginForm">
Name: <input type="text" name="form_name" size="32"/><br />
Address: <input type="text" name="form_address" size="32"/><br />
<input type="submit"/>
</form>
<?
 //If you have submitted some data thru the form, 
 //we need to send the data to the next php file.
 if($hasPostData === "true")
 {
  echo "<form action='nextPage.php' method='post' name='mainLoginForm'>";
  echo "<input type='hidden' name='name' value='". $name ."'/>";
  echo "<input type='hidden' name='address' value='". $address ."'/>";
  echo "<input type='hidden' name='info' value='". $info ."'/>";
  echo "</form>";
  echo "<script type='text/javascript'>";
  echo "function sendFormData(){document.mainLoginForm.submit();}";
  echo "sendFormData();";
        echo "</script>";
 }
?>
</body>
</html>
nextPage.php
<?
 if(isset($_POST["info"]))
 {
  echo $_POST["info"];
 }
?>
* Click here for the demo.
^ Click here for the source files of the demo.

No comments:

Post a Comment