Ok. So I am using Sessions to store data because I am making a multi page form. The thing is, I need a back button with it. I have a submit button that will take the user to the next page and store the data into sessions but I need a back button next to the submit button in case they messed up for whatever reason. Is there anyway to make a back button with php that will take them back to the previous page while showing the data they entered? heres my code of one page.
Also, I have tried using the history.go but that only works for one page.
<?php
//let's start the session
session_start();
//now, let's register our session variables
$_SESSION['opinion1'] = 'opinion1';
$_SESSION['choice1'] = 'choice1';
//finally, let's store our posted values in the session variables
$_SESSION['opinion1'] = $_POST['opinion1'];
$_SESSION['choice1'] = $_POST['choice1'];
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href='http://fonts.googleapis.com/css?family=Playball' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" type="text/css" href="engine1/style.css" />
<script type="text/javascript" src="engine1/jquery.js"></script>
<script src="jquery.cycle2.js"></script>
<title>Untitled Document</title>
</head>
<body>
<div class="nav">
<div class="container">
<h1 class="pull-left">Securing the Future of Village Walk</h1>
<div class="pull-right">
<ul class="nav nav-pills">
<li class="active">home</li>
<li>about</li>
<li>contact</li>
</ul>
</div>
</div>
</div>
<div class="ammendment">
<div class="container">
<form method="post" action="page4_form.php">
<textarea id="opinion2" name="opinion2" value=""></textarea>
<label for="Yes">Yes</label>
<input type="radio" name="choice2" value="Yes">
<label for="No">No</label>
<input type="radio" name="choice2" value="No">
<label for="Neither">Neither</label>
<input type="radio" name="choice2" value="Neither">
**I NEED BACK BUTTON HERE**
<input type="submit" value="Next">
</form>
</div>
</div>
</body>
</html>
I would first organize session data in a way that it's easy for you to correlate data entered with the page it was entered.
One possibility could be to organize session data in an array:
$_SESSION['formData'] = array(
array(... data for step 1 ),
array(... data for step 2 ),
array(... data for step 3 ),
);
So $formData[0] would hold data entered in step 1, etc.
As for the button, another submit would be enough:
<input type="submit" value="Back" />
Then, you would have to determine which page you are going back to; which you can achieve by sending a hidden field with the current page number.
<form method="post" action="page_form.php">
<input type="hidden" name="page" value="X" />
One thing to note here is that the server side process would not longer be one-per-page; instead there would be only one page_form.php where you'll have to determine the action and the page to move to (although you could use one per page and set the right action in the , there's always several solutions to any problem):
<?php
...
$page = $_POST['page'];
if ( isset($_POST['Back']) ) // Going back
{
$page -= 1; // Previous page requested
// Retrieve data from session
$data = $_SESSION['formData'][$page-1]; // $page-1 because of zero based array indexes.
...
// Dynamically load the proper page processor.
// each pageX_form.php will know how to deal with the variable $data.
include "page{$page}_form.php"
}
else
{
$page += 1; // Next page requested
$data = $_POST; // In this case, the data is whatever was entered
}
When building the form for each page, you'd have to remember to add the hidden field with the page number:
<form method="post" action="page_form.php">
<input type="hidden" name="page" value="<?php echo $page; ?>" />
If you wanted to use one server-side process per page, then you could do something like this instead:
<form method="post" action="page<?php echo $page; ?>_form.php">
The server-side process would look different, since you would not have to ask for the page number; it would be implicit.
You could just add an additional form like so:
<form action="pageX.php" method="post>
<input name="submitBackButton" type="submit" value="Back">
</form>
This can be detected as a normal GET / POST field within PHP:
<?php
if (isset($_POST['submitBackButton']))
{
// Do required actions here
}
Related
I'm wondering if it would be possible to place two forms on the same page
and saving their cookie values respectively after clicking submit buttons.
With code below, when I click submit button on the first form, its cookie value is saved successfully but when I click on the second form, second value is saved but the first value is overwritten.
<?php
setcookie('username[user111]', $_POST['user111'], time()+60);
setcookie('username[user222]', $_POST['user222'], time()+60);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>name:<?php echo $_POST['user111']; ?></p>
<form method="POST" action="">
<input type="hidden" name="user111" value="TOM">
<input type="submit" value="close">
</form>
<p>name:<?php echo $_POST['user222']; ?></p>
<form method="POST" action="">
<input type="hidden" name="user222" value="BOB">
<input type="submit" value="close">
</form>
</body>
</html>
I'd like to save both
Name:username[user111] Value:BOB
Name:username[user222] Value:TOM
If I could save the values respectively, it'd not necessary to use form submit
but if possible I'd like to use PHP instead of JavaScript.
Any advice would be appreciated.
I'm trying to create a php page where I can cycle through a database table line-by-line. I have created a page that allows me to do this but I can't seem to be able to combine the forms so that clicking the button to go to the next/previous form also submits the data entry form.
I've made a very simplified version of the code that does not have a database attached to show you what I've been doing:
<?php
session_start();
// Create an array to cycle through
$a = array('1', '2', '3', '4');
if(isset($_POST['village']))
{
$_SESSION['counter']++;
}
elseif(isset($_POST['village1']))
{
$_SESSION['counter'] = $_SESSION['counter']-1;
}
elseif(isset($_POST['testVar']))
{
$_SESSION['testVar'] = $_POST['testVar'];
}
else
{
$_SESSION['counter'] = 0;
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<title>TEST</title>
</head>
<body>
<!-- Previous value form -->
<form name="prevValue_form" method="post" action="" enctype="multipart/form-data">
<div style="float: left">
<button class="btn btn-success" name="prev" id="prev" value="prev" style="font-size: 20px;"><</a>
</div>
<input type="text" name="village1" value="testing" />
</form>
<!-- Next value form -->
<form name="nextValue_form" method="post" action="" enctype="multipart/form-data">
<div style="float: left">
<button class="btn btn-primary" name="next" id="next" value="next" style="font-size: 20px;">></button>
</div>
<input type="text" name="village" value="testing" />
</form>
<!-- data input section -->
<div id="main" accept-charset="UTF-8" class="form">
<form name="dataEntry_form" method="post" action="" enctype="multipart/form-data">
<!-- data input variable -->
tester: <input name="testVar" value="" />
<!-- Values to display if code is working -->
<br clear="all" /><br />
count: <?php echo $a[$_SESSION['counter']]; ?>
<br clear="all" />
test variable: <?php echo $_SESSION['testVar']; ?>
<!-- submit the data entry form -->
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
</div>
</body>
</html>
<script>
$("#nextValue_form button").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "next") {
$("#test_form").submit();
$("#test_form2").submit();
}
});
$("#prevValue_form button").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "prev") {
$("#test_form").submit();
$("#test_form1").submit();
}
});
</script>
Like I said above, the page works. However, I'm moving some people over from a bunch of Access databases to SQL Server and they don't like that the inputs don't automatically submit when they click the button to go to the next record. I'd imagine this is possible to accomplish, but I'm more of a database person than a PHP person and I've been having trouble with it.
Thanks for any help
Using this post as a guide, it might be worth it to just do one form with 2 buttons and fetch only the row you need instead of an array of rows and storing things into a session. I might only store the current id into session, but that is about it.
First I would create some basic functions to reduce duplication:
<?php
# General PDO query function. Needs to have the connection injected
function query($con, $sql, $bind = null)
{
$query = $con->prepare($sql);
$query->execute($bind);
return $query->fetch(\PDO::FETCH_ASSOC);
}
# Create a next function that uses the current id to find the next record
function toNextRecord($id, $con)
{
return query($con, 'select * from tablename where id = (select min(id) from components where id > ?)',[$id]);
}
# Use the current id to find the previous record
function toPrevRecord($id, $con)
{
return query($con, 'select * from tablename where id = (select max(id) from components where id < ?)',[$id]);
}
# Check for a post
if(!empty($_POST['action']) && $_POST['action'] == 'walk_table') {
# Fetch previous or next, depending on button press
$row = (strtolower($_POST['button']) == 'next')? toNextRecord($_POST['id'], $con) : toPrevRecord($_POST['id'], $con);
}
else
# Set the default to whatever record id to start on
$row = ['id' => 1];
?>
Make one form with an action (just makes it easier to differentiate actions) and the current id. Add the two buttons in. When clicked, only the one clicked will register in the post.
<form method="post" action="#">
<input type="hidden" name="action" value="walk_table" />
<input type="hidden" name="id" value="<?php echo $row['id'] ?>" />
<input type="submit" name="button" value="Prev" />
<input type="submit" name="button" value="Next" />
</form>
I'm working on a database-driven quiz that lets users select a series of answers, then submit the results via a form. It was working great, when it suddenly blew up, and I haven't been able to find the problem.
So before I get into the more complex stuff, I'd like to go back to square one and just make something simple work - like passing a hidden value to another page that echoes that value.
Here's the code for my first page # mysite/form.php:
<html>
<head>
</head>
<body>
<!-- g1/form.php -->
<div id="quiz" rel="key">
<form action="form2.php" method="post" id="quiz">
<input type="hidden" name="PreviousURL" id="url" />
<input type="submit" value="Submit Quiz" />
</form>
</div><!-- quiz-container -->
</body>
</html>
And here's the code for the second page:
<html>
<head>
</head>
<body>
<?php ini_set('display_errors', 1);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo $_POST['PreviousURL'];
}
echo 'XXX';
?>
</body>
</html>
I also tried moving the closing bracket, like this:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
echo $_POST['PreviousURL'];
echo 'XXX';
In both cases, when I click the submit button and am forwarded to form2.php, I see "XXX," but there's no value for $_POST['PreviousURL'].
I must have accidentally deleted or modified something, because it seems so simple, and it worked fine before. Can anyone tell me what the problem is?
there isn't a value for the hidden input.
In your form script you have missed out the value="" from the hidden input. This is the reason why nothing is displaying on the second page.
I am building a confirmation page and a simple shopping cart script. But I am unable to send the values by mail using the "Send" button which I have put on the end of the page.
If I don't wrap the mailer part inside the "if" condition for the button, it works and sends the stuff on page load. But as I wrap it inside the "if" condition, I get only a blank email.
UPDATE:
Inside the previous page, wich has the "Ordering" form, I have switched from method="post" to method="get".
And in the second page,
I have changed the method inside the loop from $_POST to $_GET. As for the button kept the $_POST method together with the method="post" inside the form (on the bottom). Now it works, but I can't understand why.
First page with form:
<!DOCTYPE html>
<head>
<title>Alm Chalet Menu</title>
<link href="css/template.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h2>Alm Chalet Menu</h2>
<p>Biologische Säfte </p>
<form method="get" action="order.php">
<p><input type="number" name="orange" min="0" value="0" class="count_style">
Orange</p>
<p><input type="number" name="multivitamine" min="0" value="0" class="count_style">Multivitamine</p>
<input type="submit" name="send" value="Send Menu" />
</form>
</body>
</html>
Second, confirmation page:
<!DOCTYPE html>
<head>
<link href="css/template.css" type="text/css" rel="stylesheet" />
<title>Ordered Food</title>
</head>
<body>
Your order the following:
<table id="order_table">
<tbody>
<?php
$items = '';
foreach($_POST as $key => $value){
if ($value == 0) {
continue;
}
echo "<tr><td>$key</td><td class='value'>$value</td></tr>";
$items .= "$key: $value\n";
}
if (isset($_GET['send'])) {
$message = $items;
mail("****#yahoo.com", $subject, $message, $headers);
echo "<p>Thanks for your order!</p>";
}
?>
</tbody>
</table>
<p>
<form method="get">
<input name="send" type="submit" value="Send Order">
</form>
</p>
</body>
</html>
I assume you are sending post data from some other page to this page? If so after you post to this page then submit another form using the get method, the $_POST variable will no longer have anything in it because you submitted another form to this page (via get). You need some way of saving the posted data (perhaps a php session) so that when you click the Send Order submit button the previously posted data isn't lost.
I know there are some articles about something like this but I can't figure it out.
P.S. I'm new in programming so maybe my question is stupid.
All I wan't to do is to change 4 contents inside a tag with clickable buttons (button1, button2, button3, button4)
When page loads user see only content_1.php.
<div id="content_box">
<?
include 'content_1.php';
include 'content_2.php';
include 'content_3.php';
include 'content_4.php';
?>
</div>
Maybe somebody can show an example?
Thanks.
use ajax requests, for reference use below link:
http://www.w3schools.com/PHP/php_ajax_database.asp
You can either (A) send it all to the client and do do hide-and-show on the client side entirely, or you can (B) send the first block of content and load the rest on demand (via AJAX).
There are a few things to take into consideration when choosing between the two:
How often are users going to see other than the initial content (few times → B: Send only what's needed, a few will make another request)
How much data are we talking about (little → A: Send it all every time, fewer requests)
Does include-ing a PHP file have side-effects (it shouldn't!) (yes → B: Only include what's requested)
As for the first strategy, you could:
<script type="text/javascript">
function show(box) {
for (var i = 1; i <= 4; i++) {
document.getElementById('content_' + i).style = (i === box ? 'block' : 'none');
}
}
</script>
<div id="content_box">
<div id="content_1"><?php include 'content_1.php'; ?></div>
<div id="content_2" style="display: none;"><?php include 'content_2.php'; ?></div>
<div id="content_3" style="display: none;"><?php include 'content_3.php'; ?></div>
<div id="content_4" style="display: none;"><?php include 'content_4.php'; ?></div>
</div>
Show #1
Show #2
Show #3
Show #4
NOTICE
This assumes that the interaction has to be on the same page. If a full page load is desired, just go with GET parameters and a PHP switch.
there are more solutions, but the simplest would be, if you created four links like:
show content 1
then in the PHP side you create the logic by this user input:
<div id="content_box">
<?php
switch($_GET['content']){
case 1: include 'content_1.php'; break;
case 2: include 'content_2.php'; break;
case 3: include 'content_3.php'; break;
case 4: include 'content_4.php'; break;
default: include 'content_1.php';
?>
</div>
By the way, <? ?> short tags are not recommended to use because are not anywhere supported because of configuration.
To make this you need to use some javascripts, but instead of invent your own maybe is better use something that exists. Try this http://jqueryui.com/demos/tabs/ this should be what you need. After that you can use the ajax request to make the user loads only the part that he need
good luck!
I think instead of "pure" AJAX (which is also fine but its code is a little bit lengthy and not so easy to understand) you should use jQuery's AJAX API to reach the same functions in an easy way.
For example to load a file you should use jQuery's load() function.
To be more specific, in your code it would look like this:
$('#content_box').load('content_1.php');
But I would like to show a complete example which also works in browsers without JavaScript or with JS disabled, because it also understands $_GET parameters. There are three solutions: 1. select and option tags, 2. buttons, 3. radio buttons.
So the code is the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Load contents with jQuery</title>
<!-- jQuery CDN: http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery -->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<!-- The code with jQuery -->
<script type="text/javascript">
$(document).ready(function(){
$('#change_content_select').submit(function(){
var which_to_load = $('#sel_number').val(),
source_of_file = 'data/content_'+which_to_load+'.php';
$('#content_box').load( source_of_file );
return false;
});
$('#button_1, #button_2, #button_3, #button_4').click(function(){
var which_to_load = ( $(this).attr('id')+"" ).replace('button_', ''),
source_of_file = 'data/content_'+which_to_load+'.php';
$('#content_box').load( source_of_file );
return false;
});
$('#change_content_radio').submit(function(){
if( $('input[name=nrOfPage]:checked').val() === undefined ){
alert('Select which page to load first...');
return false;
}
var which_to_load = $('input[name=nrOfPage]:checked').val(),
source_of_file = 'data/content_'+which_to_load+'.php';
$('#content_box').load( source_of_file );
return false;
});
});
</script>
</head>
<body>
<!-- Let's do it with select tags -->
<div id="content_changing_select_tag">
<b>Page to load with select:</b><br />
Which page would you like to load?
<form method="get" id="change_content_select" action="">
<p>
<select id="sel_number" name="nrOfPage">
<option value="1">1st page</option>
<option value="2">2nd page</option>
<option value="3">3rd page</option>
<option value="4">4th page</option>
</select>
<!-- We put this submit button for compatibility with browsers with JavaScript disabled -->
<input type="submit" value="Change content" />
</p>
</form>
</div>
<hr />
<!-- Let's do it with buttons -->
<div id="content_changing_buttons">
<b>Page to load with buttons:</b><br />
Which page would you like to load?
<form method="get" id="change_content_buttons" action="">
<p>
<input value="1" type="submit" id="button_1" name="nrOfPage" />
<input value="2" type="submit" id="button_2" name="nrOfPage" />
<input value="3" type="submit" id="button_3" name="nrOfPage" />
<input value="4" type="submit" id="button_4" name="nrOfPage" />
</p>
</form>
</div>
<hr />
<!-- Let's do it with radio buttons -->
<div id="content_changing_radio">
<b>Page to load with radio:</b><br />
Which page would you like to load?
<form method="get" id="change_content_radio" action="">
<p>
<input type="radio" name="nrOfPage" value="1" />
<input type="radio" name="nrOfPage" value="2" />
<input type="radio" name="nrOfPage" value="3" />
<input type="radio" name="nrOfPage" value="4" />
<!-- We put this submit button for compatibility with browsers with JavaScript disabled -->
<input type="submit" value="Change content" />
</p>
</form>
</div>
<hr />
<div>OK, here comes the content...</div>
<div id="content_box">
<?php
// default number of page to load
$defaultPageNumber = '1';
// check if content number is set
$numberOfPageToInclude = isset($_GET['nrOfPage']) ? $_GET['nrOfPage'] : $defaultPageNumber;
$options = array(
'options' => array(
'min_range' => 1,
'max_range' => 4,
));
if (filter_var($numberOfPageToInclude, FILTER_VALIDATE_INT, $options) !== FALSE) {
include 'data/content_' . $numberOfPageToInclude . '.php';
} else {
echo '<span style="color:red;">Wrong page number, including default page!</span><br />';
include 'data/content_1.php';
}
?>
</div>
</body>
</html>
And an example for the files to include:
content_1.php :
<h1>This is content <span style="color:red;font-size: 125%;">1</span>!</h1>
content_2.php :
<h1>This is content <span style="color:red;font-size: 125%;">2</span>!</h1>
content_3.php :
<h1>This is content <span style="color:red;font-size: 125%;">3</span>!</h1>
content_4.php :
<h1>This is content <span style="color:red;font-size: 125%;">4</span>!</h1>
Ask if something isn't clear.
Hope that helps someone!
(Btw. it's TESTED and WORKING.)