Retaining values for the current page when refreshing the page

hi there. do anyone of you know how to retain values of textbox values for the current page so that the values will still remain when the page is refreshed?
Thanks so much for your help in advance :slight_smile:

Could you be a little more specific about what you are trying to accomplish? This is easy to do, but the method kind of depends on what you are trying to do.

hi there, as i have set validation for the form for adding contact, therefore if someone entered a field wrongly , the whole page will be refreshed and the values written before will not be retained in the textbox and the user will have to write their details into the textbox for various fields again. Therefore, i am wondering if there is a way to retain values inside the textbox. Many many thanks :slight_smile:

Well, the best means of basic input validation is Javascript. I would be happy to walk you through the basics of implementing this approach. It helps to have the clients machine do the work on this (you can check for other things with PHP) plus you donā€™t have to reload the values they entered, you just donā€™t let them submit the form if they havenā€™t filled out all required items. Tell me about what kind of validation you are doing (form fields) and I will help you implement an easy solution to your problems

the validation is to ensure that users will have to enter all fields on the page and the validation is to check that the user has typed in the correct format for the fields too eg users have typed in 8 numbers for the telephone number field. Thanks for your help :slight_smile:

Ah, I went ahead and threw an example together for you:


<html>
<head>
<title>Demo Form Validation</title>
<script type="text/javascript">
//This function will decide whether the form can be submitted
function checkForm()
{
	//Get the form object to reference the items within it
	var form = document.forms[0];
	for(i = 0; i < form.length; i++)//form.length is the number of items in the form (submit is included)
	{
		//traversing the form elements looking for something left blank
		if(form.elements*.value == "" || form.elements*.value == null)
		{
			return false;
		}
	}
	//You could add another check here, like a regex on  an email input if you wanted
	var reg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	if(!(reg.test(form.email.value)))
	{	
		document.getElementById('emailError').style.display = "inline";
		return false;
	}else{
		document.getElementById('emailError').style.display = "none";
	}
	//You won't get to this point if you fail any of the above (True value allows the form to be submitted)
	return true;
}
</script>
<style type="text/css">
#emailError
{
	display:none;
	color:#ff0000;
}
</style>
</head>
<body>
<form action="" method="post" onsubmit="return checkForm()">
Name: <input type="text" name="name" /><br />
Email: <input type="text" name="email" /><span id="emailError">Not a valid email address</span><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

[quote=actionAction;2351148]Ah, I went ahead and threw an example together for you:


<html>
<head>
<title>Demo Form Validation</title>
<script type="text/javascript">
//This function will decide whether the form can be submitted
function checkForm()
{
    //Get the form object to reference the items within it
    var form = document.forms[0];
    for(i = 0; i < form.length; i++)//form.length is the number of items in the form (submit is included)
    {
        //traversing the form elements looking for something left blank
        if(form.elements*.value == "" || form.elements*.value == null)
        {
            return false;
        }
    }
    //You could add another check here, like a regex on  an email input if you wanted
    var reg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
    if(!(reg.test(form.email.value)))
    {    
        document.getElementById('emailError').style.display = "inline";
        return false;
    }else{
        document.getElementById('emailError').style.display = "none";
    }
    //You won't get to this point if you fail any of the above (True value allows the form to be submitted)
    return true;
}
</script>
<style type="text/css">
#emailError
{
    display:none;
    color:#ff0000;
}
</style>
</head>
<body>
<form action="" method="post" onsubmit="return checkForm()">
Name: <input type="text" name="name" /><br />
Email: <input type="text" name="email" /><span id="emailError">Not a valid email address</span><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

[/quote]

thanks for the help given. can the codes be written in other format and not by javascript? as the codes are all written in php codes. Sorry for the inconvenienced caused and trouble given by me.

No problem. No, the code cannot be translated to PHP. The point that I was making is that what you want to do is BEST handled on the client-side. Doing this with PHP will complicate your code a lot, and Javascript can handle it without any issue. Why do you need this to stay in PHP? You could really just drop a lot of my example code into your existing PHP code and you have got a solution. If you are not aware, it is not a problem to have Javascript embedded within a php page.

hi there, i understand what you mean already. how about the codes to validate the string of phone numbers to be more than 8? must it be written inside the function check form too or must it be written outside the function? thanks for those answers provided by you :slight_smile:

The problem with the javascript validation is that any user with scripts turned off or problems with their javascript machine wonā€™t be able to use the validation, therefore validation on the server side is a must.

A dual layer of validation is preferable - I disagree with the statement that validation is best handled on the client side - the point being that the server canā€™t see what the client is doing, it only gets the data down the line and acts accordingly. Someone without the javascript validation working would be able to submit anything they wanted - and if not they wouldnā€™t be able to submit anything at all!

Validation on the server side can be done by looking at the post data coming through and acting accordingly. Each of your input controls will send a value based on the user input, the data gets stored in the PHP $_POST[] vars with each element being named according to the control ID that sent it

(i.e. a textbox called ā€˜UserNameā€™ would hold itā€™s values in $_POST[ā€œUserNameā€])

All you need to do is check the page upon postback and see whether valid values have been entered into each box. You can write a function to validate a type of input which uses regular expressions or conditional statements - do it any way you feel comfortable with and test it.

Once the input has been checked, if itā€™s valid then you run your submission code, if invalid then you would not run your submission code, instead break out of the code, display any errors on screen and fill you textboxes with the values from $_POST[] so the user does not have to re-enter data.

A very simple pseudo-example:


AddControlsToArray(); // Add all the controls needing validation to an array
 
if (PageWasSubmitted) {
  if (ValidateControlsInTheArray()) { // validate the controls
    AddUserToDatabase(); // Add a user to the database as they entered all info correctly
  } else {
    GetErrors(); // Get all the controls with errors and set the error messages to display for each one
    RefillControls(); // Get the data from $_POST[] and refill the controls with the user input which was submitted so they can correct it
  }
}

[quote=Charleh;2351256]The problem with the javascript validation is that any user with scripts turned off or problems with their javascript machine wonā€™t be able to use the validation, therefore validation on the server side is a must.

A dual layer of validation is preferable - I disagree with the statement that validation is best handled on the client side - the point being that the server canā€™t see what the client is doing, it only gets the data down the line and acts accordingly. Someone without the javascript validation working would be able to submit anything they wanted - and if not they wouldnā€™t be able to submit anything at all!

Validation on the server side can be done by looking at the post data coming through and acting accordingly. Each of your input controls will send a value based on the user input, the data gets stored in the PHP $_POST[] vars with each element being named according to the control ID that sent it

(i.e. a textbox called ā€˜UserNameā€™ would hold itā€™s values in $_POST[ā€œUserNameā€])

All you need to do is check the page upon postback and see whether valid values have been entered into each box. You can write a function to validate a type of input which uses regular expressions or conditional statements - do it any way you feel comfortable with and test it.

Once the input has been checked, if itā€™s valid then you run your submission code, if invalid then you would not run your submission code, instead break out of the code, display any errors on screen and fill you textboxes with the values from $_POST[] so the user does not have to re-enter data.

A very simple pseudo-example:


AddControlsToArray(); // Add all the controls needing validation to an array
 
if (PageWasSubmitted) {
  if (ValidateControlsInTheArray()) { // validate the controls
    AddUserToDatabase(); // Add a user to the database as they entered all info correctly
  } else {
    GetErrors(); // Get all the controls with errors and set the error messages to display for each one
    RefillControls(); // Get the data from $_POST[] and refill the controls with the user input which was submitted so they can correct it
  }
}

[/quote]

hi there, what do you mean by adding user to the database? as i have already written codes for the validation and if the user has entered all fields correctly, it will then proceed to execute the database eg adding contacts or updating information etc. so why do we need to add users to database twice? and refill controls? you mean i have to write codes for this refill control function? sorry for all the inconvenience caused. and thanks :slight_smile:

Itā€™s just an example - the AddUserToDatabase function is a hypothetical function where your code should go instead - it sounds like you have already done this. The only bit you need to write is a little bit of code which refills the controls if the user has made an error

For that you just need to check the corresponding $_POST[] vars and put these values into the controls (i.e.)

echo "<textarea id='someText'>" . $_POST["someText"] . "</textarea>";

[quote=Charleh;2351717]Itā€™s just an example - the AddUserToDatabase function is a hypothetical function where your code should go instead - it sounds like you have already done this. The only bit you need to write is a little bit of code which refills the controls if the user has made an error

For that you just need to check the corresponding $_POST[] vars and put these values into the controls (i.e.)

echo "<textarea id='someText'>" . $_POST["someText"] . "</textarea>";

[/quote]

thanks alot for your help. i have understand what you are trying to say but if i want to refill the controls and i echo it under the errors. wonā€™t the controls be shown below the errors? once again, thanks :slight_smile:

No basically you will show either the blank box if the $_POST data is empty or the value if the user had filled it last time the form was submitted.

So replace the code for your input areas with either a function which outputs the correct HTML for the control or as Iā€™ve done above just injected the last $_POST data into the input area.

So you might have


<?
 // Page code in here 
?>
<html>
<form action="?submit=yes" method="POST"> 
  <textarea id="someID"><? echo $_POST["someID"]; ?></textarea>
  <? echo $errorMessages["someID"]; // assuming you have an array set up to contain error messages for each control ?>
</form>
</html>

So if the user has not input anything (i.e. the first time a form loads) the value of $_POST[ā€œsomeIDā€] will be blank, so the text area will have nothing in it.

If the user enters some text then submits the page, the $_POST data will contain a value in the ā€œsomeIDā€ index which will then get placed into the textarea

Understand it now?

[quote=Charleh;2351756]No basically you will show either the blank box if the $_POST data is empty or the value if the user had filled it last time the form was submitted.

So replace the code for your input areas with either a function which outputs the correct HTML for the control or as Iā€™ve done above just injected the last $_POST data into the input area.

So you might have


<?
 // Page code in here 
?>
<html>
<form action="?submit=yes" method="POST"> 
  <textarea id="someID"><? echo $_POST["someID"]; ?></textarea>
  <? echo $errorMessages["someID"]; // assuming you have an array set up to contain error messages for each control ?>
</form>
</html>

So if the user has not input anything (i.e. the first time a form loads) the value of $_POST[ā€œsomeIDā€] will be blank, so the text area will have nothing in it.

If the user enters some text then submits the page, the $_POST data will contain a value in the ā€œsomeIDā€ index which will then get placed into the textarea

Understand it now?[/quote]

How about editing of information? As the values in my editing information form has been passed through from the previous page and if the validation fails, all the values being passed through from the previous page will be disappeared. Sorry for all the trouble given to you by me.

If you are on an ā€˜editingā€™ information page and the user enters valid information the values should have been saved into the database - the data should be drawn from the database when the page refreshes