how to select option to submit different php page - php

drop down select "sales" go to sales.php, other options selected go to addFund.php...
<form name='searform' method='post' action='<?php echo $home;?>addFund.php'>
Search : <input type='text' id='sear' name='sear'> by
<select id='psel' name='psel' onchange='change()'>
<option value='email'>Email</option>
<option value='name'>Username</option>
<option value='domain'>Domain name</option>
<option value='sales'>Sales</option>
</select>
<input type='submit' name='sub' id='sub' value='Go' onclick='gopage()'>
<input type='submit' name='dir' id='dir' value='Direct'>
</form>
How to submit different pages

You could use some Javascript nastiness to achieve this with the change() function, but the usual way to do this is to route all requests through a controller and include() the appropriate page. For example, point your form to action.php, and in that file, do this:
action.php
<?php
if (isset($_POST['psel']) && $_POST['psel'] == 'sales') {
include 'sales.php';
} else {
include 'addFund.php';
}
...or you could just put roughly that code into addFund.php, since you only seem to have one other script that you would want to send requests to.

You could do this with javascript:
function change(el) {
if(el.value === 'sales') {
el.form.action = 'sales.php';
} else {
el.form.action = 'addFund.php';
}
}
Change the onchange to onchange="change(this)". A better way would be to check the variable on serverside and include the right file.

Change your select to this:
<select name="vote" onChange="document.forms['searForm'].submit()">
And make your form action go to something like pageChange.php where it returns a different page depending on the $_POST value.

Related

Keep select list on reload

I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.

Reload same page after form subit in HTML/PHP

I am using a get method to select options with years and months. The URL after submitting this selection looks as follows:
www.mywebsite.com/transactions/?yr=2013&mo=6
I can reload this page and the selection is still there. However, when i submit a form to add a record, the page reloads as follows:
www.mywebsite.com/transactions/?#
And the selection is gone. How can I keep the seletion and reload the exact same url after submitting the form?
I am using the following code:
<form action="?" method="post">
<SELECT options with different inputs>
<input type="submit" value="Add">
</form>
In my PHP it looks the following:
header('Location: ?yr='. $GLOBALS['yearselect'] .'&mo=' . $GLOBALS['monthselect']);
It creates the right URL after submit, only the global variables are not updated. I defined those as follows:
$GLOBALS['monthselect'] = date('m');
$GLOBALS['yearselect'] = date('Y');
And they are changed when I select an option.
You could traverse through submitted variables and add them to the HTML code.
<form action="target.php?var1=<?= $_GET["value2"]; ?>&var2=value2" method="get">
Or just use $_SERVER['REQUEST_URI'] inside action="".
Your form element probably has an attribute action="#".
You could replace this with the original request uri (assuming you use the POST method, if you use GET the query parameters in the form's action attribute will be overridden in most browsers.
<form method="POST" action="<?= $_SERVER['REQUEST_URI'] ?>">your form</form>
In your PHP code, after you get the values by GET method, use the header() function as :
header("Location: www.mywebsite.com/transactions/?yr=2013&mo=6");
It will redirect to the page with the form.
EDITED:
This is a sample code for your need:
<?php
$years=array(1999,2000,2001,2002,2003,2004);
if(isset($_POST['year']))
{
/*
Do your coding here
*/
echo <<<EOT
<form action='{$_SERVER['PHP_SELF']}' method='POST'>
<select name='year'>
EOT;
for($i=0;$i<6;$i++)
{
if($years[$i]==$_POST['year'])
echo "<option value='{$years[$i]}' selected='selected' >{$years[$i]}</option>";
else
echo "<option value='{$years[$i]}'>{$years[$i]}</option>";
}
echo <<<EOT
</select>
<input type='submit' value='Add'>
</form>
EOT;
}
else
{
echo <<<EOT
<form action='{$_SERVER['PHP_SELF']}' method='POST'>
<select name='year'>
EOT;
for($i=0;$i<6;$i++)
{
echo "<option value='{$years[$i]}'>{$years[$i]}</option>";
}
echo <<<EOT
</select>
<input type='submit' value='Add'>
</form>
EOT;
}
?>
It will print the first value of the drop-down list on the first time, and after that it'll save the values.
Inside form tag action attribute should b set to the page which handles your request,i think u have set action='#' .
Please specify more detail.so that i can help u

Setting PHP cookie from dropdown menu

I have a PHP script designed to allow users to decide which language a page is displayed in. The information is stored in a cookie and then read when needed to display the correct content.
Currently, I use an HTML dropdown box to allow the user to select the language and then they must press the form submit button to set the cookie. How can I make it so when they select the language in the dropdown menu it automatically selects that and submits the form? I hope you can understand my question.
My current PHP code is:
<?php
$user_lang = null;
if (isset($_POST["setc"])) {
$expire = time() + 60 * 60 * 24 * 30;
setcookie("mycookie", $_POST["sel"], $expire);
header("location: " . $_SERVER["PHP_SELF"]);
} else if (isset($_COOKIE["mycookie"])) {
$user_lang = $_COOKIE["mycookie"];
}
?>
<meta charset='utf-8'>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<select name="sel" size="1">
<option value="en"<?php echo (!is_null($user_lang) && $user_lang === "en" ? " selected" : ""); ?>>English</option>
<option value="es"<?php echo (!is_null($user_lang) && $user_lang === "es" ? " selected" : ""); ?>>Español</option>
<option value="fr"<?php echo (!is_null($user_lang) && $user_lang === "fr" ? " selected" : ""); ?>>Français</option>
<option value="de"<?php echo (!is_null($user_lang) && $user_lang === "de" ? " selected" : ""); ?>>Deutsch</option>
</select>
<input name="setc" value="save setting" type="submit">
</form>
Change your select tag to:
<select name="sel" size="1" onchange="this.form.submit();">
to make the form submit when users selects a language.
If you wish to do that without JavaScript you can use multiple submit buttons method instead:
<input name="set_language[en]" value="English" type="submit">
<input name="set_language[es]" value="Español" type="submit">
<input name="set_language[fr]" value="Français" type="submit">
<input name="set_language[de]" value="Deutsch" type="submit">
Processing this form is simple as it is:
if (isset($_POST["set_language"])) {
$language = key($_POST["set_language"]);
// $language contains user-selected language code now
}
This can't be done with a select field but without JavaScript or any other client-side scripting language.
You need to do it using JavaScript:
<select name="sel" size="1" onchange="this.form.submit();">
Or if you use jQuery:
$("select[name='sel']").change(function() {
$(this).parent().submit();
});
This will submit the form whenever a user changes value in the dropdown list.
You can add an onchange event to the select:
<select onChange="document.forms[0].submit();">
Remember that it's a good thing to leave the submit button for those users who don't have javascript enabled. You can hide the button using javascript, so it won't clutter the window of those that doe have a regular browser.
I think you have to use javascript like the others said, but you can also use the submit button as a backup if the user doesn't have javascript activated:
<noscript><input value="save setting" type="submit"></noscript>
And then, since the submit button will only be shown when the user has javascript disabled, you will need to add a hidden input to check if the form has been submitted on the server side
<input type="hidden" name="setc" value="true" />
The answer is in JavaScript not PHP. You could do it unobtrusively with JavaScript like this:
<script>
window.onload = function() {
document.getElementById("idOfDropDown").addEventListener("change", function() {
document.forms["formName"].submit();
});
}
</script>

php how to grab the selected value from a drop down list?

<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.

Preserving previous while adding new one on a form

I have this form that comes with some parameters from another page. I want to preserve those values and add a sortby parameter, but every time I hit submit all the parameters disappear, but the new sortby parameter.
How can I preserve the parameters from the previous page and add or change just the orderby parameter.
<form name="formSearch" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>" method="GET">
<select name="order_by" id="order_by">
<option <?php if( isset($_REQUEST['order_by']) && $_REQUEST['order_by'] == 1) { echo "selected"; } ?> value="1">Ultima Modificacion (Reciente)</option>
<option <?php if( isset($_REQUEST['order_by']) && $_REQUEST['order_by'] == 2) { echo "selected"; } ?> value="2">Ultima Modificacion (Viejo)</option>
<option <?php if( isset($_REQUEST['order_by']) && $_REQUEST['order_by'] == 3) { echo "selected"; } ?> value="3">Precio (Mayor to Menor)</option>
<option <?php if( isset($_REQUEST['order_by']) && $_REQUEST['order_by'] == 4) { echo "selected"; } ?> value="4">Precio (Menor to Mayor)</option>
<option <?php if( isset($_REQUEST['order_by']) && $_REQUEST['order_by'] == 5) { echo "selected"; } ?> value="5">Marca/Modelo (A to Z)</option>
<option <?php if( isset($_REQUEST['order_by']) && $_REQUEST['order_by'] == 6) { echo "selected"; } ?> value="6">Marca/Modelo (Z to A)</option>
</select>
<input name="submit" type="submit" />
</form>
Add
<INPUT type='hidden' name='OPT1' VALUE='<?php if( isset($_REQUEST['OPT1'])) { echo $_REQUEST['OPT1']; } else { echo "" } ?>
since you need to pass them as hidden input fields.
OPT1 is the name of the parameter to preserve - add as many of these as you have parameters
If you wish for the fields/values to actually show, then :
Drop type='hidden' to display them and be editable
Make them disabled input fields to display them and not be editable.
However those 2 options need to be done cleanly, e.g. if the old value came from radio button, you need to display and pre-populate same radio button setup, etc...
It seem that is the way "form" work if you use the method "GET", So, if I need to preserve the values and need to use "GET" I would need to add a bunch of hidden fields like it was suggested. But I was trying to avoid that. If someone knows a better way, please let me know, if not this would be a solution:
" method="GET">
$v){
echo ''."\n";
}
?>
Now, If you don't need to use "GET" in the result form, just change the method to "POST" and it will work fine.
Note if you are coming from another form, that form needs to be "GET" for this to work.
Search Page -> Use Get
Result Page w/ Sorting form -> Use Post
The simplest way to persist the data would be to make sure the fields responsible for populating the values in question are present on the current page. If they're not supposed to be visible to the user anymore on the page in question, you can set them to <input type="hidden" name=fieldname" value="value_set_on_previous_submit"/> . Or if they should still show, just ensure that their values are set to the submitted ones.

Categories