Using Javascript to Preserve Form Contents During Browser Refresh

Marion Bates <mbates at whoopis.com>

Last modified: December 31 1969 16:00:00

This is a mini-howto on how to do one very useful thing with JavaScript.

The reason this came about was, we had a database- and PHP-generated webpage which was set to automatically refresh via a META refresh in the document HEAD every ten seconds in order to update the display of some chat contents pulled from a MySQL database. The same page also had an HTML form for adding an entry to the chat. The issue was that if a user began to type an entry, but did not hit "submit" before the next meta refresh, their unfinished input would be lost. We didn't want to have to make the user open a new window for input, or otherwise change the "mode"; this turned out to be the best/easiest/most-compatible answer for us. YMMV.

  1. Embed the following code in your form page's HEAD section, adjusting the red items accordingly:
    <script type="text/javascript">
    <!--
    var seconds = 5;
    
    onload = function(){
     setInterval('refreshWithVars()', seconds*1000);
    }
    
     function refreshWithVars() {
     var thefield = document.theform.thefield.value;
     window.location = 'http://www.yourwebserver.com/index.php?thefield='+thefield;
    }
    
    //--></script>
    

    Note the "var thefield = ..." line; it is key that your page's form and field names match. I.e. "theform" needs to match your page's "form name=" attribute, and "thefield" needs to match the particular form field. "document" and "value" do NOT change.

  2. Now, in the body:
    <p>Here is a form field that should autofill on refresh:
    <form name="theform" action="index.php">
    
    <?php
    
    if (isset($_GET['thefield'])) {
    	$thefield = $_GET['thefield'];
    	echo "<input name=\"thefield\" value=\"$thefield\">";
    }
    else {
    	echo "<input name=\"thefield\">";
    }
    
    ?>
    
    <input type="submit">
    </form>
    
  3. Upload and test. Start typing into the box, then pause and wait for the refresh; the input box should automatically reappear with whatever you'd typed. Click here for a functional example.


Get Euro-style oval stickers for Geeks!

NEW -- the "magic/more magic" light switch cover!
Click here for the story.

References/Resources: