vlevsha
vlevsha

Reputation: 265

Retaining data in HTML form

I have an HTML form. Let's say I fill out all the fields and submit it (PHP script runs here). Then I want to go back to the form using "Back" button of my browser. What I see is the empty form. What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?

Thank you!

Upvotes: 2

Views: 2483

Answers (4)

Timo Huovinen
Timo Huovinen

Reputation: 55623

Store the value in a session

session_start();

//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question

if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}

then on the form page

<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />

obviously the above can be simplified, but for a example's sake it's better this way.

(make sure to clean out the old form data eventually)

Upvotes: 1

Brad Westness
Brad Westness

Reputation: 1572

Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.

Example:

// submission page
session_start();
if(isset($_POST)){
  // save the posted data in the session
  $_SESSION["POST"] = $_POST;
}

Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:

// form page
session_start();
if(isset($_SESSION["POST"])){
  // previous POST data has been saved
  // build the form with pre-defined values from $_SESSION
  ...
} else {
  // no previous data
  // build the form without pre-defined values
  ...
}

Note that you must call session_start() before outputting any HTML.

Upvotes: 1

tpae
tpae

Reputation: 6346

You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.

Example:

Storing data:

$_SESSION['data'] = $_POST['item1'];

In the HTML Forms:

<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />

Upvotes: 0

Nev Stokes
Nev Stokes

Reputation: 9779

If you use the "Back" button of your browser then your browser is responsible for re-populating your form data.

Upvotes: 3

Related Questions