php输出结果[关闭]

I am getting confused as I read various posts about the typical task I am trying to perform, no doubt countless others have done it before. So at this point in 2013 what is the best practice solution to achieve the following:

  • I have an html page which asks the user for a number of values, x1, x2, .....xn.
  • There may be 10 to 20 such inputs. As such I don't want them to be lost or to have to be re-inputted again for whatever reason.
  • perform calculations based on user inputs then output the results (eg. y1, y2, y3..y5).
  • As suggested by some of the posts here, I tried "echo" (for PHP), that works fine. However, it shows the results in a new page so the user input is no longer visible.
  • I want the user to see both - their input and the resultant. That way they can print if they want to and see all info on one page.
  • I prefer to use "basic" technologies, ie. technologies that most users can use, that they don't have to click OK on some warning, change some setting on their browser, accept some thing or other etc..

Thanks in advance!

  1. Create inputs with html.
  2. Choose between reloading page or AJAX
  3. If you choose reloading then use

code:

  <form action="nextfile.php" method="POST">
   <input type="text" value="" name="y1" />
   <input type="text" value="" name="y2" />
   <input type="submit" value="calc me" name="submit" />
  </form> 

Then in nextfile.php you need get values with $_POST and if you want them to be saved use $_SESSION

For example

<?php 
session_start();
if(isset($_POST['y1']) && isset($_POST['y2']))
{
    $_SESSION['res'] = (int)$_POST['y1'] * (int)$_POST['y2'];
}

The code above will perform calculation on two inputs with name y1 and y2 and save them in session.

If you want AJAX then you need to visit this page and see examples

You should think of JavaScript solution because it will fit your needs and no server code is needed.

The simplest way is to submit the form to the same page and repopulate the input fields:

// calc.php
<?php

    if (isset($_POST['foo'])) {
        echo 'Result: ', $_POST['foo'] + 1;
    }

?>

<form action="calc.php" ...>
   <input name="foo" value="<?php if (isset($_POST['foo'])) echo htmlspecialchars($_POST['foo']); ?>">
   ...
</form>

The more modern version would be to submit the calculations via AJAX and populate the result via Javascript without reloading the page.