Fixing the Back Button for Forms
Problem
A user enters a page with a form and the request has parameters that determine the selected values for some of the form elements. Then the user changes those selections and submits the form. When the user arrives at the results page, they decide to hit the Back Button to change some of their selections. When the previous page with the form loads again, all of their prior selections are missing and they have to start over. This is a very frustrating experience for the user, and potentially impacts online business. This makes it an important problem to solve for Web developers.
Solution
When the form is submitted, write a simple cookie that contains the values or selectedIndex of the form elements. At the bottom of the page containing the form, do a simple cookie check conditional with JavaScript. If the cookie exists, use the values in the cookie to repopulate the form correctly. It’s important to not have this functionality inside a function that is called by the onload
event, as some browsers will not fire the onload
event on a back button. Having the JavaScript just before the closing body
tag works well.
If you’re using AJAX type functionality to grab data from the server, you can just use the cookie values to retrieve that information and repopulate the form.
Now for the real problem… When the user arrived, the URL had parameters that had values used to populate some of the form elements. When the Back Button is used, the browser respects those same parameters. So how do you determine whether or not a user is viewing the page for the first time or as a result of the Back Button? It’s actually quite simple. Add a hidden
field to your form that has a random number (like milliseconds) as the value. Then add that value to the cookie that gets written when the form is submitted. If the user hits the Back Button, then the cookie number will match the hidden
field number, at which point you use the cookie values to repopulate the form. Otherwise, use the request parameters to reset the form. Note: in order for this to work correctly, you need to make sure that there is no cache-busting stuff going on that forces the browser back to the server for the page. The page needs to come from cache when the Back Button is used or the random number value in the form will change all the time. Tail your access log to ensure the server isn’t being hit when the Back Button is hit. So don’t use anything like:
<meta http-equiv="Expires" content="0" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Cache-Control" content="no-cache" /> <% response.setHeader("Expires","0"); %>