Getting a page to memorize what has been input

I normally only have one or two inputs on a form, and editing such is no problem. However, I’d like to find a way to do this so that my form memorizes what has been input. I’m pretty certain this can probably be best done using Ajax or Javascript, but I’m not on the best of terms with either.
The plan is to have some error checking above the form, with relevant error messages, but not sure how to get the form to display what has been input already.
Code begins:

                echo '<form action="createrequest.php" method="POST">';
                echo '<label for="Location">Select Location:</label>';
                echo '<select name="location" id="location" required>';
                echo '<option value="Please select">Please select</option>';
                foreach ($pnames as $name => $pid) {
                    echo '<option value="' . $pid . '">' . $name . '</option>';
                }
                echo '</select>';
                echo 'Department: <input type="text" name="dept"><br>';
                echo '<label for="aptdt">Appointment (date and time):</label>';
                echo '<input type="datetime-local" id="aptdt" name="aptdt">';
                echo '<p>Does the client use a walking aid:</p>';
                echo '<input type="radio" id="none" name="aid" value="0" checked>';
                echo '<label for="none">None required</label><br>';
                echo '<input type="radio" id="haszim" name="aid" value="1">';
                echo '<label for="haszim">Has zimmer</label><br>';
                echo '<input type="radio" id="reqzim" name="aid" value="2">';
                echo '<label for="reqzim">Requires zimmer</label><br>';
                echo '<input type="radio" id="haswc" name="aid" value="3">';
                echo '<label for="haswc">Has wheelchair</label><br>';
                echo '<input type="radio" id="needswc" name="aid" value="4">';
                echo '<label for="needswc">Requires wheelchair</label><br>';
                echo '<p>Blue badge?</p>';
                echo '<input type="checkbox" id="blue" name="blue" value="No"><br>';
                echo '<label for="blue"> I have a blue badge</label><br>';
                echo '<p>Assistance</p>';
                echo '<input type="radio" id="noass" name="help" value="0" checked>';
                echo '<label for="noass">None required</label><br>';
                echo '<input type="radio" id="needass" name="help" value="1">';
                echo '<label for="needass">Needs some help</label><br>';
                echo '<input type="radio" id="bringass" name="help" value="2">';
                echo '<label for="bringass">Bringing help</label><br>';
                echo 'Notes: <input type="text" name="notes"><br>';
                echo '<c><button type="submit">Next</button></c>';

Code ends.
I am using the POST method, and I assume that there is some way to assign the already entered values from $_POST?
Thanks.

You would use the submitted form data, if any (the null coalescing operator ?? comes in handy for the initial case where there is no submitted form data), to populate form field values, to preselect options, or to precheck checkbox/radio fields. Note: any dynamic value you output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting.

You should use an intermediate array variable to hold a trimmed working copy of the form data, that gets used throughout the rest of the code. There are two reasons for this - 1. to leave the original $_POST data as is, in case it is needed, 2. when you get to the point of editing existing data, you can simply query for and fetch that data into the same intermediate array variable.

If you have more than 2-3 form fields, you should dynamically validate and process the form data, and dynamically build the form, by defining the expected fields in an array, along with a display label, field type, validation rules, processing rules, … for each field. You would then loop over this defining array to control what general purpose code does, instead of writing out bespoke code and markup for every field.

Here’s a, non-dynamic, example for a single form field -

// initialization
session_start();

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// post method form processing
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
	// inputs - fname (start with a single field)
	
	// trim all the data at once
	$post = array_map('trim',$_POST); // if any input is an array, use a recursive trim call-back function here instead of php's trim
	
	// validate the inputs
	// first name
	if($post['fname'] === '')
	{
		$errors['fname'] = "First Name is required.";
	}
	
	// validate the rest of the inputs here...
	
	// if no errors, use the form data
	if(!$errors)
	{
	}
	
	// if no errors, success
	if(!$errors)
	{
		$_SESSION['success_message'] = 'Your data has been processed.';
		die(header("Refresh:0"));
	}
}

// get method business logic - get/produce data needed to display the web page,

// html document - this is an incomplete document and only shows the parts necessary for this demonstration
?>

<?php
// display and clear any success message
if(!empty($_SESSION['success_message']))
{
	echo "<p>{$_SESSION['success_message']}</p>";
	unset($_SESSION['success_message']);
}
?>

<?php
// display any user/validation errors
if($errors)
{
	echo '<p>'.implode('<br>',$errors).'</p>';
}
?>

<?php
// display the form
?>
<form method='post'>
<label>First Name:<br><input type='text' name='fname' value='<?=htmlentities($post['fname']??'')?>'></label><br>
<br>
<input type='submit'>
</form>
1 Like

Thanks for a very clear and explicit reply. One remaining question. How do you memorize the selected value in a dropdown list, i.e. when the form is redisplayed, how do you set this from your $post array?
Thanks.

echo "<option value='$somevalue'";
IF ($valueselected == $somevalue) {
echo " selected";
}
echo ">$displayvalue</option>

As you loop over a list ($array) of option choices to produce the output, you would determine if the current choice should be preselected -

<label>Field name: <select name='field_name'>
<option value=''>Choose an option</option>
<?php
foreach($array_of_choices as $value=>$choice)
{
	// determine if the current choice should be preselected
	$sel = ($post['field_name']??'') == $value ? 'selected' : '';
	?>
	<option value='<?=$value?>' <?=$sel?>><?=$choice?></option>
	<?php
}
?>
</select>
</label><br>

What an elegant solution, and I get to learn to use some new php syntax.
Many thanks.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.