submit a form when hitting the browser back button - php

I have a page for asking queries to an SQL database. Its only purpose is to allow students to exercise. Depending on the students activity the page rewrites itself with new content so that the student may enter a query, have the resulting table shown or get an error message.
All is working through forms that post data to the same page.
However, if a student uses the back button or the forward button (after hitting the back button) data gets lost as I cleanse the $_POST variable content to get ready for new action.
There is, however, a "go back" button that assembles data to restore the previous page by POSTing the required data. Is it possible to use some kind of technique, javascript, html5, PHP or whatever to actually submit the form that posts the assembled data when hitting the browser back button?
I am using HTML 5, PHP 5 and some JavaScript (not JQuery but if it gives me an option ...)

you can use the html5 storage since if user not fill the full form or close the browser the data will lost on close browser and not submit it form not fill
to check html5 storage
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
use onkeyup to store like
$("#title").keyup(function(){
var articel_title = $("#title").val();
localStorage.setItem("articel_title",articel_title);
localStorage.getItem("articel_title");
});
and next time when user open the form just show the content stored
to clear use
localStorage.removeItem("articel_title");

As suggested in the comments you could store the post data in the session, for example every time a new query is posted you could add it:
$_SESSION['queries'][] = $_POST;
Then you could allow the users to go back / forward through this with some form of loop:
<ul>
<?php foreach($_SESSION['queries'] as $k => $v) : ?>
<li>Some link structure</li>
<?php endforeach; ?>
</ul>

Related

jQuery: Store dynamic form with values and reload on back button

I've Googled and searched on SO quite a bit for this unique problem, but not really finding my exact solution.
I have a basic form with X number of inputs. At some point in the form, the user as the freedom to add inputs via button click if needed. When they submit the form, it goes to another page to collect the posted form data, but I want the ability for the user to click "Back" (or send them back programmatically) if the submit fails.
I have error checking setup prior to submit via javascript, but there are other things (such as a PHP mailer) that could fail and I want them to be able to resubmit their data.
The issue of course is when the browser clicks back, it - at best - refreshes the initial form that was in the DOM with input data, but I lose all of the dynamically added inputs.
I want to capture the form/data in a session and have it repopulate the DOM with the submitted version created by the user on click back.
The closest I've come is doing something like this on SUBMIT:
var theForm = $('#myForm');
sessionStorage.setItem('formData', JSON.stringify(theForm.clone(true).html().toString());
And this on postback/click back:
$('#myForm').replaceWith(JSON.parse(sessionStorage.getItem("formData")));
The problem here is I get my form, but not the data! Do I need to iterate over each input to get my data put back in the recreated form?? Why doesn't it grab the data when .clone(true)ed?
Here's the answer I ultimately got to work.
Upon form validation, I set the session to hold the form data like so:
var theForm = $('#MyForm');
sessionStorage.setItem('formHTML', JSON.stringify(theForm.clone(true).html()));
theForm.find('input,select,textarea').each(function(){
sessionStorage.setItem(this.name,this.value);
});
Then, when the DOM loads again, I have this that checks for the session and populates the form with data if it exists:
$(document).ready(function(){
if (sessionStorage.getItem("formHTML")) {
$('#MyForm').html($.parseJSON(sessionStorage.getItem("formHTML")));
}
$('#MyForm').find('input,select,textarea').each(function(i,elem){
var sessItem = elem.name, sessValue = '';
if (sessValue = sessionStorage.getItem(sessItem)) {
if(elem.type=='radio' && elem.value==sessValue){
alert(elem[i].type+' has value of "'+elem[i].value+'"');
$('[name='+sessItem+']')[i].prop('checked',true);
}
else if(elem.type=='textarea'){
alert(elem.type);
$('[name='+sessItem+']').val(sessValue);
}
else
{
$('[name='+sessItem+']').val(sessValue);
}
}
});
});

Submit two forms to the same page

I have been on this site all day and can't seem to find what I need - no duplicate post intended.
I have a form containing a link which calls a modal popup containing a different form.
###### PARENT PAGE #############
<form...>
...
link
...
</form>
**** MODAL POPUP ****
<form...>
...
<input type="submit" />
</form>
**** END MODAL POPUP ****
### END PARENT PAGE #############
When I submit the form in the modal popup, the parent page is refreshed to show the updated info in the corresponding section of the page; except that the first form is not submitted and when the page refreshes to update the necessary section, the contents of the first form is lost.
I have tried using ajax to refresh only the necessary section of the page but that doesn't work as the sections that need refreshing use php variables with contents from mysql.
The system does what it needs to do and I don't mind the refresh. But I need a way to keep the user data entered into the first form.
Is it possible to submit the first form at the same time as the second to the same php page or any other way of preserving the user data in the first form on page reload without submitting it.
You cannot do this with pure php. You'll need javascript and write it in a way that when you hit submit on the modal it 'puts' the information back into the parent form.
One way is to make the modal form submit button not an actual submit button.
You might even be able to get away with taking the filled out section dom elements in the modal injected back into the parent form. Some jquery plugins already do this. For example colorbox
Here is a working example using only ONE <form> tag and jquery colorbox. http://jsbin.com/olalam/1/edit
I am not a php developer, so I'll suggest an alternative approach.
Before you refresh the page, you can serialize the form and store the data locally (e.g. in a cookie) then restore the data back into the form. Granted, that will require a bit more JS code, but should get you what you want.
UPDATE: Since you mentioned that you might need a little assistance on the JS front, here is some guidance:
Grab the jquery.cookie plugin here.
Grab the jquery.deserialize plugin here.
Use the following code as a starting point.
.
// the name of the cookie
var cookieName = 'myCookieName';
function beforeSubmit() {
// serialize the form into a variable
var serializedForm = $('#id-of-form').serialize();
// store the serialized form
$.cookie(cookieName, serializedForm, { path: '/' });
}
function afterRefresh() {
// read the cookie
var serializedForm = $.cookie(cookieName);
// de-serialize the form
$('#id-of-form').deserialize(serializedForm, true);
}
HTH

php $_POST and pagination $_GET

I face a problem whenever the user tries to browse to second page via $_GET if they have submitted $_POST data.
if(!isset($_POST['submit'])) {
//search input box
}
else {
//search details output
//pagination code
}
Whenever user press page 2, it shows //search input box back.
I want search to show page 2 and not //search input box back.
This is because you are not sending POST data to the second page.
$_GET and $_POST are set per request. If you want to save the first POST data, you will need to use sessions and store it in the session, or return the POSTed data to your page and have it be resubmitted.
As #Alan says... page 2 isn't receiving POST data, so submit is not set and it thinks the starting form should be shown again. A second GET variable (eg page) to track the results-page, will allow all three pages (start, page1+submit, page2)
if (isset($_REQUEST["page"])) {
//No data received, but reviewing & page-display code should go here
} elseif (isset($_POST["submit"])) {
//POST-processing code goes here
// Page-switching URL should be something like:
// Page 2
} else {
//Nothing posted, not paging - show input
//search input box
}
Don't forget to store your POST data somewhere temporarily so that you have data to display on the pages.
Seams like your logic is twisted. Just look at your code with aditional comments:
// if POST submit is NOT set
if(!isset($_POST['submit'])) {
// show search input box
}
You shouldn't be submitting a search request via POST. Searching is the kind of read-only operation ideally suited to GET requests and the query string. All you have to do then is modify the query string to include something like &page=2 to add pagination to your links.
A better way to do it is to split your form processing into its own script. This makes it more organized and more logical so that you can do things like POST to it via AJAX easier. A tip for solving the other problem I see you are having is if you are having a multipage form you should store the data they submit on previous pages somewhere. A common place is in session data. There are other ways to do it like storing it all in a javascript data object until the form is completed. Look into using a framework, they will help.

Saving dynamically added text input to MySQL

Hey all, using this method jQuery append() and remove() element i'm adding text inputs to a document. i'm using this php
if($_POST['cp_slider'])
{
$array=$_POST['cp_slider'];
foreach($array as $cp_slider)
{
if(strlen($cp_slider)>0)
{
echo '<li><input type="text" name="cp_slider[]" value="'.$this->options["theme_slider"].'" /><img src="images/delete.gif" /></li>';
}
}
}
The value was created like this:
if ($_POST['to_action'] == 'save') {
$this->options["theme_slider"] = $_POST['cp_slider'];
update_option('artTheme', $this->options);
}
But what i see in the value of every input after submitting the form is: Array as a word.
UPDATE
I figured it out and it's working fine. The value gets it's real value, i've just changed the foreach line
from this
foreach($array as $cp_slider)
to this
foreach($array as $this->options["theme_slider"])
But there is still one problem there. After i submit the form, the data from inputs submits very well. But when i go to another page with in the application and then i'm comming back to the page with this inputs, they are simply not there, they just disappear from the page.
this question seems to vague there are many ways to submit form data so I guess start with a form then choose ajax or maybe you want to look at jquery validation
HTH
If you are trying to save the data, your jQuery will have to send the request to a PHP script that will take the input and put it into the database somehow.
User Makes Edits
Presses 'Save'
The Save button fires off a jQuery
AJAX request that sends the
appropriate data to a PHP script that
processes/sanitizes it and then puts
it into the database
If you don't make a call to another script, jQuery will just be updating the HTML seen in the browser and your PHP scripts won't know anything about it.

PHP Multiform Validation and Redirection

I have buy.php with a form where you enter items, quantity, shipping data, etc.
When you click the Submit button, it posts back to buy.php ($_SERVER['PHP_SELF']) and does some data validation.
If there are fields missing or errors, they are highlighted. If everything is correct, I save the $_POST data in $_SESSION variables, then do a header('Location: check.php'), where I display the data so the buyer can check the info one last time before actually buying.
Now, if I'm in check.php and hit the Back button to buy.php so I can change stuff, the browser asks if I want to resend the POST data. I'm trying to avoid that.
Anyone have any good advice or good practices for PHP Multiform validation?
Also, if I had n pages for the user to fill, buy.php, buy2.php, ... buyn.php before check.php would the same ideas still hold?
You could do a redirect to buy.php after saving to the session object, which then does a server redirect to check.php, it would mean when the user clicks back, they're going back to the GET request not the POST request
Yes - I agree with above. I ALWAYS do a redir away from the last post, so clicking back bounces them back without that error OR re-submissions. it also avoids complications. u can always tag the redir link page with a ?m or &m (i.e.: page.php?m) and have this at top of page: (use elseif there after)
if (isset($_GET['m'])) {
echo 'order placed.';
}
else {
//...
}
You can have it all on one page too. Just name the submit buttons submit1, submit2, like: (bear in mind if you use an image for submits, it becomes $_POST['submit1_x'] :)
if (isset($_POST[submit1]) {
//validate + save session data from form1
//display form 2
} else if(isset($_POST[submit2])) {
//validate + save session data from form2
//display form 3
} else {
//display first form
//<input type="submit" name="submit1" value="Continue">
}

Categories