Loading, please wait...

picture of me
Joe Rushton Fullstack Web Developer

Remembering Form Values Using Sessions - PHP/jQuery

15th March 2017 Reading Time: 4 mins
Tags: Javascript PHP

If you want to create the best possible user experience for your website, this is definitely a nice to have if you have a lot of web forms.

So imagine you have a form with a bunch of different fields, some of which may encourage a lengthy response (e.g. a free text field that asks for the users feedback).

You wouldn't want your users getting frustrated or put off at having to re-populate the form if they decide to come back at a later date after already populating it.

 

The Code

We'll start with the PHP side which basically involves storing the input name and value in a session. It's only a couple of lines of code, check it out

<?php
session_start();

// Check the POST variables aren't empty
if (!empty($_POST['name']) && !empty($_POST['value'])) {
  // Store the name of the input and the value (the users input) in a SESSION variable
  $_SESSION['inputs'][$_POST['name']] = $_POST['value'];
}

For my example, I've created a file named `save_inputs.php` and just placed it in the root directory of my project. We will be making a POST request to `save_inputs.php` through AJAX - which is a feature of Javascript that allows you to make a request to a web page, similar to submitting a form, without having to physically start a new page request. (AKA asynchronous Javascript)

In this case, we will be making a request whenever we simply "change" an input. That would look something like this - assuming you already have jQuery included in your file somewhere:

// standard way of starting all jQuery code
$(document).ready(function() {

        // attach an event to all inputs/textareas where we fire an anonymous function whenever they change
        $('input, textarea').on('change', function() {
          // This is the data that we will be posting to our PHP file
          var data = {
            // set name equal to the current inputs html attribute "name"
            name: $(this).attr('name'),
            // set the value equal to whatever the user has entered in the current ($(this)) input
            value: $(this).val()
          };

          // execute the AJAX POST request
          $.post('save_inputs.php', data);
        });
});

 This targets all inputs and textareas but it can be adjusted to only target specific elements using specific css selectors.

 

The last step is to simply output the SESSION variables in the appropriate input. There are many different ways that you may want to do this depending on your project setup but for simplicity, I will check if the relevant session variable is not empty and output it, otherwise print out a blank string.

<textarea name='input-2' id='input-2' class='form-control'>
   <?php echo !empty($_SESSION['inputs']['input-2']) ? $_SESSION['inputs']['input-2'] : ''; ?>
</textarea>

The above snippet will output the appropriate session variable if it's available. This is for a textarea, for other inputs it will vary slightly:

Text Inputs

<input type="text" id="input-3" name="input-3" value="<?=$_SESSION['inputs']['input-3'];?>" />

Select Dropdowns

<?php 
   if (!empty($_SESSION['inputs']['input-4'])) {
     // store in a easier to reference variable to make the HTML look nicer
     // .. and prevent having to do an empty check for each option
     $val = $_SESSION['inputs']['input-4'];
   } else {
     $val = '';
   }
?>
<select name="input-4" id="input-4">
   <option <?= $val == 'val-1' ? selected="selected" : ''; ?> value="val-1">Value 1</option>
   <option <?= $val == 'val-2' ? selected="selected" : ''; ?> value="val-2">Value 2</option
</select>

Of course there are tonnes of different ways you could write this, you may be using a templating engine such as Smarty or Twig which allow you to do all of the empty checks and logic in a separate PHP file and simply pass your variables to the view to declutter your view files.

It's important to note that I stored the input values in an array key called "inputs" because you'll need to empty it once the form has been submitted and validated and this makes it super easy:

unset($_SESSION['inputs']);
Back to Homepage

Find me on social media