How to keep radio selected states when hitting browser back button? - php

I am handling a survey multistep form with many radio sets.
They have some default states
User operates over them to select his preferences.
Now the client wants when hitting either browser back button or the side navigator links (a set of links pointing to previous stages of the survey) to have the radio states the user previously chose.
Here is how the navigator looks like:
<ul>
<li>Step1</li>
<li>Step2</li>
<li>Step3</li>
</ul>
There is only one $_SESSION that collects data throughout the survey.
I know I can load information directly from $_SESSION but I need to replace the default states when the request comes from the navigator links/ back button.

After posting form, you can save values in the session. When accessing previous page again (or even first load it), read session's values and check specified radios. If you access page first time, there will be no data in the session, so no one will be checked.
You can also store selected values lively with JavaScript and cookies.

There are two main approaches to this, basically you are saying that the chosen state of the radio's need to be saved between different pages of your form.
So when you return to a page you were on previously but without submitting, the choices should still be the same.
There are two key approaches, server side with PHP or client side with Javascript
PHP
You can set any link on the website to submit the form and you could save the radio selections, then when you create the form you can check the previously selected value
This information could be saved in $_SESSION but they'd need to submit the form each time they changed the page (you could change the links to do this)
Javascript
You could write some javascript that remembered the content of the selections and stored them in the users browser as a cookie, this could update everytime they clicked a button. When the page loads the javascript would check for cookies (or local storage) and would load the previous options.
When they finish and submit the form you'd clear the javascript
Basic example
$('form input[type=radio]:checked')
Once I have more information I'll flesh out this answer further

A very simplified possible solution:
<?php
session_start(); // this needs to be at the top of all pages using $_SESSION (before anything else) else $_SESSION will always be empty
if($_POST['vehicle']){
$_SESSION['checkbox1'] = $_POST['vehicle'];
}
print_r($_SESSION); // remove this line after testing. It will show you the contents of the $_SESSION, which is handy for seeing when variables are set within it
?>
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input type="checkbox" name="vehicle" value="Bike"<?php if($_SESSION['checkbox1'] == "Bike"){ echo " checked"}?>>I have a bike<br />
<input type="checkbox" name="vehicle" value="Car"<?php if($_SESSION['checkbox1'] == "Car"){ echo " checked"}?>>I have a car <br />#
<input type="submit" value="Go" />
</form>
</body>
</html>
You could add a unique id generated at the first page in a hidden input area that when posted could form part of the session variable name. From there the information would be indexed in the $_SESSION under that variable name making it easier to pull the data back out or to create a new form session as it were.
Hope I haven't lost you.

Related

How to clear an HTML Form, even the form's initial values?

I have an HTML form that sends information via post to a PHP file.
On the user's second visit the page should remember the last search input. So if on their first visit they were looking for pencil then on their second visit, the form would already have prefilled the Product Name input with pencil. I'm doing this via a session variable that is shared between the two files.
For example this is what my code looks like:
<label for="minPrice">Minimum Price</label>
<input id="minPrice" type="text" value="<?php echo $_SESSION['minPrice'];?>" name="minPrice">
<input class="clearForm" type="reset" value="Clear Form">
As you can see, I'm setting the value of the input field using the session variable. Which means the initial value on the second visit of the input will be the value of $_SESSION['minPrice'], so the typical type="reset" for clearing forms doesn't work. Reset just resets the form to it's initial values.
My first thought was to unset the session variables, but that wouldn't change the current values in the input fields of the form.
There are 2 ways to make it happen
Using PHP session the correct way
Using Javascript local storage
Using PHP sessions
Make sure your .php file has session_start() at the top.
Now you need to request the server to save the value(s) you wanna use on "the next visit". This means, requesting the server without refreshing the page through an HTML form submit, using AJAX.
Following JS snippet will post a form to the server, you can modify what to post as easily as eating an apple pie.
fetch(url, {method: 'POST', body: new FormData(form)})
But you have to POST when the user types something so add an eventListener that triggers the fetch method.
document.getElementById('minPrice').addEventListener('keydown', () => {fetch...})
url is the name of the file or the url you wanna POST to,
form is the form you wanna submit, in case you wanna submit some input field(s) alone, replace new FormData(form) by {minPrice: document.getElementById('minPrice').value} and so on.
assign the fetch method to a variable and you can get the server's response using
variable.then(res => res.json()).then(response => //do whatever you want)
On the server side, get the value(s) using the superGlobal $_POST, such as $_POST['minPrice'] and you can save it in the $_SESSION['minPrice'] variable and whenever the user reloads or makes a second visit, the $_SESSION['minPrice '] will assign the last written minPrice to the input field.
Using Javascript local storage
localStorage is built-into javascript and is quite easier to use. Read more about localStorage on MDN docs. Use
localStorage.setItem('minPrice', document.getElementById('minPrice').value)
And assign the localStorage value to the field on every page load.
document.getElementById('minPrice').value = localStorage.getItem('minPrice')
That's it!
Take a look at this !
Make page to tell browser not to cache/preserve input values
Stop browser from filling textboxes with details
Alternatively, try adding this in Jquery :
$("form :input").attr("autocomplete", "off");
Use JavaScript to clear out the values of the form fields.
Something like:
<button onclick="() => {
document.querySelectorAll('input').value = '';
}" />
That way when you click the reset button, it sets all inputs value to empty string.
If you're never going to want the field autofilled by the browser it seems like you'd simply want to use the autocomplete="off" flag on the input field you desire to be dynamically filled by your php script.
You can read more about the specific of this on the MDN docs.
Basically though you'd take the input, store it as a session variable, load the next page and populate the search variable into the input field as a value and turn the autocomplete functionality off so that the browser cannot override the value you provide from the session value.
The support for for this seems fairly broad. and should in most cases prevent the browser from overriding whatever it has stored for the field.
If you're still running into issues with it filling you cvould maybe look to adding some javascript functionality with the reset() function. However depending on how this is fired it might actually end up overriding whatever you populate with the PHP function at the time the DOM is actuall rendered

Hold selected state of checkbox in pagination

If I check some checkboxes on page 1 and then click Next to go to page 2 and then come back to page 1, the selected checkboxes are no longer checked. Is there any way to resolve this in PHP or JavaScript?
Since the data need to be accessed from different pages, you have to persist it somehow. The easier option is using the session store, or you can use a table in your database (note that the two strategies are not so different when you go to the bare, since you can easy back the session store with a table in your database). Your problem is basically the same as the shopping cart in ecommerce sites.
Note that if you choose the session and the data is stored inside an object, you may need to provide a way to serialize/deserialize it.
uhm.. i would probably go for an AJAX solution.
<script>
function saveMe(){
//ajax function which calls a page that sets the session data
}
</script>
<input onclick="saveMe()" <?php if(isset($_SESSION['chk'])){echo "checked";} ?> id="chk" name="chk" type="checkbox" />
Yes you need to create pagination using jquery because when you reload page to come back from page2 or ...
you will see your selected check box will be unchecked.
Here a reference for you to make jquery data table with pagination
http://www.sprymedia.co.uk/dataTables/example_multi_col_sort.html
http://www.jqueryrain.com/2012/04/best-ajax-jquery-pagination-plugin-tutorial-with-example-demo/

A form with 3 submits; how to keep data for final submit?

I have created a PHP form which requires the user to select a postcode from a list of postcode values.
The user presses submit two times:
- once to go to address select menu which will display a select drop-down with values
- second presses "ok" button to select the address corresponding to his postcode value
I need to keep the value of the selected postcode value for when the form gets submitted. I have tried setting up the postcode drop-down value chosen in a SESSION... but it gets lots when user presses form submit.
How can I keep all the form values even after refreshing the page when the user presses one of the submits?
"How can I keep all the form values even after refreshing the page when the user presses one of the submits?"
Reading your question I didn't understand if each of the form submits actually gets submitted to the server, but I'm going to assume so. I'm also assuming you're trying to use PHP sessions to accomplish this.
When the user submits the form, save the values server-side in a PHP session
//Start the session
session_start();
//Save the values
$_SESSION["foo"] = $_POST["bar"];
...
If, after choosing the address, the user gets redirected to the initial form and you want to populate that:
//Start the session
<?php
session_start();
?>
<!-- Populate HTML form based on previously submitted values -->
<input type="text" name="foo" value="<?php echo $_SESSION["foo"] ?>" />
...
After the final submit you should have all the submitted values saved in the $_SESSION array. Don't forget to always session_start() before trying to handle anything session related.
The short answer is I don't think you can track form data across multiple forms.
I haven't seen your project and so might not fully understand the requirements, but I would suggest you consider using AJAX. Check out the jQuery post() manual, it's really simple actually. This has the advantage of allowing you to update the page once your first form has been completed.
EDIT: Sorry I meant you can't access multiple form data in a single $_POST. Of course you could store it in $_SESSION (remember to start your session properly).

Php, passing data between pages without using the url?

I have a php page that has a form that asks for an e-mail. When you press the send button, it gets to another php page, which gets the form data and does its stuff. I need to then be able to go back to the old page (the one that contained the form) and give it some data so that it will be able to change itself and say "You've sent your e-mail successfully, and will not display the form.
How do I do it?
Sessions probably
http://us2.php.net/manual/en/book.session.php
You can either use sessions or cookies, to not depend on the URL cookies have always to be enabled.
Check the PHP Manual (Sessions and Cookies).
Options:
1) Set a cookie (or use a session variable, which is kind of the same thing)
2) Use a separate thank-you page. After you've processed the form, redirect to http://www.mysite.com/thankyou
3) Process the form on the same page as itself. If your form is at http://www.mysite.com/myform, then at the top of that page have a little
if ($_POST)
// process form
// display thank you
else
// display form
Good luck!
If the user is just seeing data that they've entered anyway, you can just use hidden form fields:
<input type="hidden" id="lang" name="lang" value="en" />
That way you can continue to POST new forms and pass the data down the lane. That's the easiest thing to do without having to write a single extra line of PHP code.
You could also store each section in a database and save each section as-added. That would give you the added benefit of having partial data in the case of a browser crash or whatever, depending on how many parts your form is. You could then pass just an ID to the DB table row and retrieve the data for display.

Php page refresh , get the post values from formm

i got a jquery upload and crop script and i am trying to use it.
First i have a 1.html file which has a form, which requires some texts and image. After submitting the form it goes to main.php where it checks for some image properties and if successful it refreshes the page using header("location:".$_SERVER["PHP_SELF"]);
So if i place my $_POST['name'] i get the value from 1.html . Now when the image in displayed after page refresh there is one more option to select the thumbnail and upon selecting the thumbnail there is one more page refresh, to display the final images (both bigger and thumb). Now my problem is for second page refresh i am not able to get the fields which i had posted from 1.html. Any suggestion would be highly appreciated. Thanks
With that header refresh you are losing every information. Drop the refresh and do consecutive forms: you need to propagate the values you need from the first form, using hidden input fields in the forms that follow
<input type="hidden" value="<?php echo $value_from_original_post; ?>">
or you can store the value(s) of interests in session variable(s).
Alternatively, you can use an AJAX solution which requires no reload or page change, but it's a bit more work (and you might not want javascript).
You can not store states between pages unless:
Keep rolling the value(s) forward as hidden input type if it's a form submission.
Temporarily save value(s) as cookie until consumed.

Categories