I am building a site on wordpress and I have encountered a problem that I am not quite sure how to solve.
The Situation:
User makes a selection from a <select> tag on one page and submits their choice
User arrives at a page featuring the same <select>. When the user selects an option, it displays content corresponding with that option using a little bit of jQuery.
-
$('.result').hide();
$('#servicearea').change(function() {
$('.result').hide();
var optionValue = $ (this).attr('value');
$('#'+optionValue).show('fast');
});
The Problem:
I need the selection from the first page to carry over to the second page then run this script.
Solutions:
I'll be honest, I don't know where to start with this, maybe cookies? I was hoping there was a jQuery type of solution as I am sort of comfortable with jQuery.
Any suggestions would be appreciated.
javascript doesnt know what you have posted to the page.
you can put the value into the javascript from php with something like this:
<script>
doSomething(<?=$_POST['selected'?>);
</script>
or you can put it into a hidden form field
<input type="hidden" id="hiddenField" value="<?=$_POST['selected']?>">
and catch the value with
$('#hiddenField').val()
Hidden form fields will work. But if you decide to go with PHP sessions instead, take a look here.
From the above link...
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
// Works if session cookie was accepted
echo '<br />page 2';
// Or maybe pass along the session id, if needed
echo '<br />page 2';
?>
After viewing page1.php, the second page page2.php will contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.
<?php
// page2.php
session_start();
echo 'Welcome to page #2<br />';
echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);
// You may want to use SID here, like we did in page1.php
echo '<br />page 1';
?>
UPDATE
Judging by your snippet, I believe you would set the session variable by doing something like this:
<form action="" method="post">
<select type="select" name="servicearea" >
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['optionValue'] = $_POST['servicearea'];
}
echo $_SESSION['optionValue'];
?>
Related
iamiI have a selection tag and and options that can do task in the page , but the problem is that it just does that in just the index page and not and the others... this is my code:
region.php
(isset($_POST["company"])) ? $company = $_POST["company"] : $company=1;
if(isset($_POST['selectedRegion'])){
$region = explode( "|" ,$_POST['selectedRegion']) ;
$_SESSION['regCode'] = $region[0];
$_SESSION['selection'] = $region[1];
$regionCode = $_SESSION['regCode'];
}else if(isset($_SESSION['regCode'])){
$region[1] = $_SESSION['selection'];
$regionCode = $_SESSION['regCode'] ;
}else{
$regionCode = 'DEF';
$_SESSION['regCode'] = $regionCode;
}
<form id="regionSelect" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onchange="this.form.submit();" >
<select id="selectedRegion" name="selectedRegion" size="1" autocomplete="off">
<option style="border-bottom: 1px dashed #000" value="<?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != 'DEF'){ echo "".$_POST['selectedRegion']."";}?>" selected="selected"><?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != "DEF"){ echo "".$region[1]."";}else{echo "--------";} ?></option>
<option value="ny">New York</option>
<option value="miami">Miami</option>
</select>
<input type="submit" value="Enter Region" />
</form>
process.php
<?php if(!isset($_SESSION)){ session_start();}
if(isset($_POST['selectedRegion'])){
$region = $_SESSION['selectedRegion']=$_POST['selectedRegion'];
if($region == "ny"){
echo "new york selected";
}
if($region == "miami"){
echo "miami selected";
}
?>
The index.php and all the other pages of the site have the region.php and the process.php included, but my problem is that any time that i do a selection it just does the action on the page that is in... and if i want the action to be made in another page i would have to press the option again. is there anyway that i can do the action of my selection work on page change and all the pages of my site? thanks
The solution you are looking for consists of these steps:
you evaluate the selection you receive at session start from the client, according to what the user has chosen. So just what you have so far.
you store that selection in a session variable. See the php documentation for the basic use of a session variable. It just boils down to:
session_start();
$_SESSION['region'] = $_POST['selectedRegion'];
you create a switch statement based on that session variable in all scripts that should react on that user choice:
session_start();
switch ($_SESSION['region']) {
case 'ny':
// do something
break;
case 'miami':
// do something
break;
default:
// do something
}
With this the user has to make his choice only once inside a single session (returning requests). You can offer that selection on the entry page and/or on all pages, just as you like. You can enhance that by storing that inside a persistent user profile, if you have an account management.
In addition some more information, as a reaction to your additional information as you provided by editing your question.
Your general approach is probably into the right direction, great. There are a few issues you have to correct though. I can only hint to them, since you offer only snippets of your scripts.
In 'process.php' you have this line:
$region = $_SESSION['selectedRegion']=$_POST['selectedRegion'];
This is obviously invalid syntax, you cannot have two assignments inside a single statement. At least that does not do what you want it to.
not sure if this conditional really belongs there:
if (isset($_POST['selectedRegion']))
It is fine if 'process.php' is the script meant to SET the session variable. In all other scripts obviously $_POST['selectedRegion'] is not set, since the user did not make a choice / was not offered a choice. So there you cannot test or use that variable, you just use the session variable directly.
there are a few other things, but as said you are on the right track.
This approach does work, it is the "normal" approach to this. So don't get frustrated, you will sort this out. In general: your code is a little confusing, too many separate variables where it is unclear what purpose they save. Why the distinction between region, regionCode and selectedRegion. Why isn't a single variable sufficient? Try to simplify your code, this will help to get this to work.
Value of $_POST['selectedRegion'] will not be available always. You should store this value in session like $_SESSION['selectedReg']=$_POST['selectedRegion']; during the form submission.
<form id="regionSelect" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onchange="this.form.submit();" >
<option style="border-bottom: 1px dashed #000" value="<?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != 'DEF'){ echo $_SESSION['selectedRegion'];}?>" ><?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != "DEF"){ echo $_SESSION['selectedRegion'];}else{echo "--------";} ?></option>
<option value="ny">New York</option>
<option value="miami">Miami</option>
</select>
<input type="submit" value="Enter Region" />
</form>
I have a form and table like this.
What I'm trying to do is - If the select box is selected with a value, it is stored in session on submit(post) and i would like to retain the session value in select box.
If there is session value, it will display the session value in select box, else it will display all.
The below case is not working in my case.
What the below code do is - first time it doesn't set the session value. If I submit again(second time) the session is stored with the first value(first submit value) and it goes on like this.
Hope this question is answerable.
EDITED:
<?php
session_start();
if($_POST){
$_SESSION['book_id'] = $_POST['book_id'];
?>
<table class="table table-bordered" cellpadding="0" cellspacing="0" border="0">
My Table Content
</table>
<?php } ?>
<form method="post">
<?php print_r($_SESSION); ?>
<select name="book_id" class="form-control">
<option value="0">Select Book</option>
<?php while($row=mysql_fetch_array($book_query)){?>
<option <?php if(isset($_SESSION['book_id']) && $row['book_id'] == $_SESSION['book_id']) echo 'selected="selected"'; ?> value="<?php echo $row['book_id'];?>"><?php echo $row['book_name']; ?></option>
<?php }?>
</select>
<input type="submit" value="submit">
</form>
EDIT:
I have print_r for the session value.
What happens is - When I submit the form first time, the session value is empty.
When I submit it second time, the first submit value is stored in session, and it goes on.
Thanks,
Kimz
A few notes:
It seems you are mixing up book_id and book_name.
Also, you don't seem to submit a "book_name" in your form.
The "if($_POST)"-block is executed when the page loads, and not when the form is sent. So essentially, you first try to select something by a value in your session, and then afterwards store said value into your session.
First of all make sure you have session_start() included somewhere.
Secondly, try changing your IF on the options to this:
<?php if(isset($_SESSION['book_id']) && $row['book_id'] == $_SESSION['book_id']) echo 'selected="selected"'; ?>
Notice the isset. Without that on page load you are likely to get a PHP undefined index error.
Finally, try placing the 'if ($_POST) {}' before the form is displayed, so the session gets set before the form is displayed. Currently you wont see any changes until you refresh the page again, this is because the form is being rendered and then the session is set from the POST data afterwards.
I have url variables that was submitted from a form from the previous page. So my url looks something like site.com/submitted.php?first_name=hello&last_name=bye.
Now I am using a link to keep my submitted variables while I go to my second page
<a href="secondPage.php?first_name=hello&last_name=bye>pageLink</a>
On this second page, it's basically a drop-down using the select tag with a submit button that generates a table from mysql server which then links back into the same page. It looks like:
<FORM ACTION="secondPage.php?first_name=hello&last_name=bye" METHOD="GET">
<select name='selectedOption' >
<option value="op1">option1</option>
<option value="op2">option2</option>
<option value="op3">option3</option>
</select>
<INPUT TYPE="SUBMIT" VALUE = "Search">
</FORM>
But lets say I choose option1 and submit, my url does not keep the variables first_name and last_name but it just replaces it :
secondPage.php?selectedOption=op1
instead of:
secondPage.php?first_name=hello&last_name=bye&selectedOption=op1
Any help is appreciated.
I'm not sure how you want to pass data around but here is a suggestion to get the values you want with php.
Change this:
<FORM ACTION="secondPage.php?first_name=hello&last_name=bye" METHOD="GET>
to this:
<form action="secondPage.php" METHOD="post">
Your code for secondPage.php coud look something like this:
// the 'if' statements aren't necessary. just an idea for simple server-side
// validation
if(isset($_REQUEST['selectedOption']) && $_REQUEST['selectedOption'] != ''){
$option = $_REQUEST['selectedOption'];
}
if(isset($_REQUEST['first_name']) && $_REQUEST['first_name'] != ''){
$fname = $_REQUEST['first_name'];
}
if(isset($_REQUEST['last_name']) && $_REQUEST['last_name'] != ''){
$lname = $_REQUEST['last_name'];
}
All the values you need to do whatever with are now in $option, $fname, and $lname
You say your new to php, welcome :), and don't ever trust user input. You should take some time and read about SQL Injection.
Hope some of this helps and good luck.
ON THE SECOND PAGE. In form make two hidden fields <input type="hidden" value="<?php echo $_REQUEST['first_name'] ?>" name="first_name"/> and
<input type="hidden" value=""<?php echo $_REQUEST['last_name'] ?>"" name="last_name"/>
my suggestion use post method
Basically, I've been working myself with something exactly like that, but I've found a great solution and a great approach in my own opinion.. let me give you some bit and piece of code as an example if you don't mind ^_^..
to be organised and clear what you did is : -
##**FIRST PAGE** : -
the url: - secondPage.php?first_name=hello&last_name=bye <--- this was the result..
Then you travelled to the 2nd page: - <-- result was still associated
##**SECOND PAGE** : -
$firstname = $_GET['first_name'];
$lastname= $_GET['last_name'];
<FORM ACTION="secondPage.php?first_name=<?php echo $firstname; ?>&last_name=<?php echo $lastname ?>" METHOD="POST">
<select name='selectedOption' >
<option value="op1">option1</option>
<option value="op2">option2</option>
<option value="op3">option3</option>
</select>
<INPUT TYPE="SUBMIT" name ="submit" VALUE = "Search">
</FORM>
##**THIRD PAGE** The page that the form is going to go to: -
$option = $_GET ['selectedOption'];
// you can also get the other data on this page through same method i've done on page two..
<select name="gamelist" id="gamelist">
<option value="1">Backgammon</option>
<option value="2">Chess</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit" />
i want to grab the selected value and place in in a var
any idea?
thanks
Depends on your form tag.
<form method="post">
Will pass the value to $_POST['gamelist']
While
<form method="get">
Will pass the value to $_GET['gamelist']
Ofcourse, only after hitting the submit button. As morgar stated, this is pretty basic form procession. I doubt you've used google or followed a tutorial, this is almost one of the first things one learn when working with forms and PHP. We arent here to give you full solutions, take this as an example and create the full page yourself:
if($_SERVER['REQUEST_METHOD'] == "Y") {
$choice = $_Y['gamelist'];
// other stuff you want to do with the gamelist value
} else {
echo '<form method="Y" action="file.php">';
// the rest of your form
echo '</form>';
}
Replace Y with either GET or POST.
$choice = $_REQUEST['gamelist']; //works with get or post
$choice = $_POST['gamelist']
if it is a POST, or $_GET if not.
Let's say I have a HTML form:
USA
CDN
And I select option 1 (USA)
Then a php page
Ok, duh, works fine and echo's "1"
How can I display "USA" as well? So in essence, I want to pass along the option's TEXT also. How could I do this?
You would either need to change the option value on the HTML page to be the text you want displayed (poses a XSS security hazard) or on the page that's displaying the text, you'd need an array where all the values match with the forum input.
Ex:
$names[1] = "USA"; $names[2] = "CDN";
Then when you want to display it, you'd call $names[$selection] to output the text.
Another option you can consider is using javascript to update a hidden HTML element on the submitting page when the user makes their selection (using onUpdate). This information would be passed along with the submitted form data. Not the most secure or reliable of options, but an option nonetheless.
The client's browser will not post back anything beyond the form element's name and value - you would have to incorporate additional form fields and Javascript (or change the element's value) to post "USA".
I suggest having a copy of the same data structure you used to print the form.
For example, if you were to do it all in one PHP page...
<?php
$countries=array('USA','CDN');
?>
<form action='?' method='post'>
<select name='country'><?php
foreach($countries as $key=>$country){?>
<option value='<?php echo $key;?>'><?php echo $country;?></option>
<?php
} ?>
</select>
<input type='submit'>
</form>
<?php
if(isset($_POST['country'])){
$chosen=(int)$_POST['country'];
if(!isset($countries[$chosen])){?>Unknown country selection, wtf<?php exit; }?>
<div style='margin-top:20px;'>You selected <?php echo $countries[$chosen];?></div>
<?php }
Another option is to ditch the numeric value altogether, and just use the country name as the value of the option. However, for verification, you'll still want the list of values. Check the differences in this example...
<?php
$countries=array('USA','CDN');
?>
<form action='?' method='post'>
<select name='country'><?php
foreach($countries as $country){?>
<option value='<?php echo $country;?>'><?php echo $country;?></option>
<?php
} ?>
</select>
<input type='submit'>
</form>
<?php
if(isset($_POST['country'])){
$chosen=preg_replace('/[^\w]/','',$_POST['country']);//this isn't strictly necessary, since the next line checks if the value is in your original array - but filtering input is a good habit!
if(!in_array($_POST['country'],$countries)){?>Unknown country selection, wtf<?php exit; }?>
<div style='margin-top:20px;'>You selected <?php echo $chosen;?></div>
<?php }