Sticky form in PHP to retain input data & selection with validation without any client Libraries
Without using any client script like JQuery or Ajax , we can retain the data entered by user and validate the same. After validation the form will be submitted to processing page.
What is sticky form?
Whenever the form is submitted the page is refreshed so we must hold the user entered data if form data validation is not cleared ( user not fulfilled all the requirments ). The main perpuse is user need not enter the data again.
Creating the form
Inside our PHP area we will create the form so the variables we can assign to value attribute of the input elements.
Collecting the form data
This page will submit to itself as we have assigned blank value to action attribute of the form.
Once the user submits the form the data will be available to the same page. We kept one hidden tag todo which we will be monitoring to execute the validation code part or not . If this form is submitted then the hidden element todo will carry the data ( post-data ) . By using one if condition we will keep the full validation code inside it.
$status="OK"; // flag for validation
$msg=""; // validation message for user
// collect user entered data //
We will check the variable $gender the name attribute of the radio button, based on the value of this we will assign the string checked to one of the three variables ($r1,$r2,$r3).
$msg .=" Select Gender <br>";
}// end of switch for gender
}//end of gender checking
We can keep one of the three radio buttons in selected condition based on the variables set as above.
<input type=radio name=gender value=male $r1> Male
<input type=radio name=gender value=female $r2> Female
<input type=radio name=gender value=other $r3> Other
Getting textarea data
We must maintain the minimum length required for the textarea.
If user has checked the I agree checkbox then the variable $agree will hold the value yes.
$ckb='checked'; // set the value to check
$msg .="Must agree to conditions ";
The variable $ckb we will use with our checkbox.
<input type=checkbox name=agree value=yes $ckb> I Agree
Submitting the form if validation is cleared.
If all the validations are cleared then our flag ( $status ) will hold the value OK, using this we can submit the form to our processing page. This part of the code should be after the form is displayed ( loaded ) as we are using form name attribute form1 which is part of DOM object.