www.webdeveloper.com
Results 1 to 7 of 7

Thread: Save form data on reload

  1. #1
    Join Date
    Mar 2008
    Posts
    175

    Save form data on reload

    Just now, I wrote the title to this post then pressed back then forward on my browser. The title was still there. Then I hit reload - STILL there!

    The only way I know how to keep form data is saving it to a $_SESSION variable, but the only way I know how to trigger the save is with a form activated POST, then doing $_SESSION = $_POST. The problem with this, of course, is nothing is saved if they don't hit submit first.

    How is it usually done?

  2. #2
    Join Date
    Aug 2006
    Location
    Michigan
    Posts
    1,046
    try this:

    PHP Code:
    //Get the script name
    $url_script_name=$_SERVER["SCRIPT_NAME"];

    // Request
    $name $_REQUEST['name'];
    $age   $_REQUEST['age'];

    //Form
    $form =<<<FORM

    <form action="
    $url_script_name" method="post">
    Name: <input type="text" name="name" id="name" value="
    $name" />
    Age: <input type="text" name="age" id="age" value="
    $age" />
    <input type="submit" />
    </form>

    FORM;

    echo 
    $form

  3. #3
    Join Date
    May 2008
    Location
    AK
    Posts
    84

    Smile

    That effect might be a feature of the browser. It remembers form fields unless the browser is closed or force-refreshed with ctrl-F5 which forces the browser to fetch new content and not use residual memory or internet cache.
    "A chisel in one hand, a fly swatter in the other."

  4. #4
    Join Date
    Nov 2007
    Posts
    53
    another way is in the form tags make the value
    <?php print "$_POST"['name']?>

  5. #5
    Join Date
    Mar 2008
    Posts
    175
    Phill,
    That code is basically how I am doing it now, but the problem is that I can't save the form fields if the user doesn't press send. I need a way to save them even if I click reload or back without ever pressing send on the form.

  6. #6
    Join Date
    May 2008
    Location
    AK
    Posts
    84

    Smile

    As is, this ajax script is just setup to handle text inputs and elements with readily available value attributes, unlike select boxes or radio buttons.

    You will need to replace the "Path/To/Filename.ext" in each source code.

    Untested! might need a bit of tweaking and tuning.

    Javascript File:
    Code:
    var http
    function rememberField( obj ){
    	http=GethttpObject();
    	if (http==null){
    		return;
    	} 
    	var url="Path/To/filename.php";
    	url=url+"?ajax="+Math.random();
    	// Modify param to work with a select box or radio button, etc if needed.
    	var param = obj.name+'='+obj.value
    	http.onreadystatechange=stateChanged;
    	http.open("POST",url,true);
    	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	http.setRequestHeader("Content-length", param.length);
    	http.setRequestHeader("Connection", "close");
    	http.send(param);
    } 
    
    function stateChanged(){ 
    	if (http.readyState==4 && http.status == 200){ 
    		try{
    			eval(http.responseText);
    		}catch (e){
    			// Uncomment this alert if your not sure ajax is working correctly.
    			//alert('Ajax Responce Syntax Error!');
    		}
    	}
    }
    
    function GethttpObject(){
    	var http=null;
    	try{
    		// Firefox, Opera 8.0+, Safari
    		http=new httpRequest();
    	}catch (e){
    		// Internet Explorer
    		try{
    			http=new ActiveXObject("Msxml2.http");
    		}catch (e){
    			http=new ActiveXObject("Microsoft.http");
    		}
    	}
    	return http;
    }
    HTML File:
    HTML Code:
    <html>
    	<head>
    		<title>Save form data on reload</title>
    		<script type="text/javascript" src="Path/To/Javascript.js></script>
    	</head>
    	<body>
    		<form action="Path/To/filename.php" method="POST">
    			First Name: <input type="input" name="firstname" value="::firstname::" onchange="rememberField(this)" /><br />
    			Last Name: <input type="input" name="lastname" value="::lastname::" onchange="rememberField(this)" /><br />
    			<input type="Submit" value="Submit" />
    		</form>
    	</body>
    </html>

    This method separates the PHP script from the Html code. So when linking to the page, make sure you link to the PHP.

    To test how the ajax is behaving, type the url filename.php?ajax&firstname=chazzl replacing the filename, form field name, and value as necessary.

    PHP File:
    PHP Code:
    <?php
        
        
    // Load HTML
        
    $strHtml file_get_contents('Path/To/Htmlfile.htm');
        
        
    // Start session
        
    if( false === isset($_SESSION) ){
            
    session_start();
        }
        
        
    // Catch an AJAX request
        
    if( isset($_GET['ajax']) ){
            
    // Save the information
            // This can be made for explicit fields for security if needed.
            
    foreach( $_POST AS $key => $value ){
                
    $_SESSION[$key] = $value;
            }
            
    // Stop the script... we don't want anything to print to the screen
            // on an AJAX request.
            
    exit();
        }
        
        
    // Fill in Html namespaces
        
    foreach( $_SESSION AS $key => $value ){
            
    $strHtml str_replace("::$key::"$value$strHtml);
        }
        
        
    // Cleanup namespaces.
        
    $strHtml preg_replace("'::[[:alnum:][:space:][:punct:]]*?::'"''$strHtml);
        
        
    // Display parsed Html
        
    echo $strHtml;
        
    ?>
    When a user types something into the form fields, ajax will send that information to your php script server side while they continue to fill out the form. You could have the information save to a cookie so that the info will remain even after the browser closes or write the info straight into a database instead of assigning it to a session variable.

    I'm sure this won't be the fix all, but it should be a good starting point if you chose the ajax way. :P But there are the rare few users that have javascript disabled to consider when using ajax.
    Last edited by Chazzl; 05-22-2008 at 01:18 AM.
    "A chisel in one hand, a fly swatter in the other."

  7. #7
    Join Date
    Mar 2008
    Posts
    175
    That's a pretty intense solution for saving form fields. I like it! I will try to implement it tonight and I'll get back to you. Thanks

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles