Remembering php form data to display currency all over a website - php

I've set up a currency conversion dropdown in a wordpress site.
The only thing missing is that every time I load another page, the currency will reset as the form selection was 'forgotten'.
Any ideas how to do this? I tried a suggested js cookie that I saw here, but it doesn't work.
This is what I got so far:
<form name="myform" id ="myform" method="post">
<select name="currency-select" id="sort" onchange="submitform();">
<option value="" selected="selected">Currency</option>
<option value="0">U.S Dollars (USD)</option>
<option value="1">Euros (EUR)</option>
<option value="2">British Pounds (GBP)</option> `
</select>
</form>
js:
function submitform()
{
document.myform.submit();
}
I tried using this code as recommended here but it doesn't really work out for me, I think I didn't do it the right way -
<?php
`session_start();`
if (isset($_POST['currency-select'])) {
$_SESSION['sort'] = $_POST['sort'];
}
?>
I added the $_SESSION to the form as well:
<option value="0" <?php if($_SESSION['sort'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
UPDATE
I've made a few tests. The session seems to be saved (as I echoed it on a few pages while refreshing etc.) I guess the only problem now is related to the form itself. Even with the right session number, I can't get it to select the right option.
I've tried two methods, but both does not work:
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo 'selected="selected"';?>>U.S Dollars (USD)</option>
or
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo "selected";?>>U.S Dollars (USD)</option>

I'd store the selected value in a $_SESSION['selected_currency'] variable and the cross check and select it when the drop down is being populated with the currency list.
Assuming that the sessions are working, I will use something like below to keep the currency selected in your drop down.
<select name="currency">
<?php
foreach($currency as $value){
if($value->currency_code == $_SESSION['currency']){
echo "<option value='$value->currency_code' selected='selected'>$value->currency_name</option>";
} else {
echo "<option value='$value->currency_code'>$value->currency_name</option>";
}
}
?>
</select>
There could be shorter ways, I am using this for illustration purposes.

For permanent retain of data you only have a few possibilities, the easiest to implement are $_SESSION, $_COOKIE or in a Database.

You have two options to do that
1st is by adding a field to the options.php page and save your data then get back your data from the options.php for that you've to use update_option('nameOfField_form','nameOfFieldDb'); and get_option('nameOfFieldDb').
and 2nd option is by jquery.ajax(); method save your data in options.php
you may find these links helpful codex
get_option
update_option

Related

How to convert session variable into POST

ok so i have two selection boxes, upon me pressing submit on the form it takes the POST data and creates a session variable for each of them. These session variables are then used to fill the selection box with what the user has selected. However, i need to reuse the data as POST after it is submitted, but its my html is saying the field is blank even though it is displaying the session variable.
So im thinking the actual selection box is empty when filled with the session, even though i can see it?
I need to manipulate this data later on, so how can i make my php recognize it as POST after my form has been submitted.
if any more code is needed please let me know
<select name="team-1" required>
<option value='Holder' disabled selected>
<?php
if(isset($_SESSION['t_team1'])){ //echoes currently set team
echo $_SESSION['t_team1'];
}else {
echo "Team 1";
}
?>
</option> <!--Placeholder for Select-->
<?php
while($rows = $teamSet->fetch_assoc()){ //Fills select with teams matching cup
$teamName = $rows['team_name'];
echo " <option value='$teamName'>$teamName</option>";
}
?> <?php mysqli_data_seek($teamSet, 0); ?> <!--RESETS WHILE LOOP, DUPLICATE AFTER EVERY TEAM "WET"-->
</select>

HTML Dropdown menu with autosuggestion and auto updation

I am trying to develop a webpage based on html, css. I am using PHP for server side scripting.
I want a dropdown menu to be displayed with available options, But at the same time I need this drop down list to accept text. so I can choose from dropdown list as well from the text box whatever I want.
I found one solution for the above scenario and working fine, but what extra I want that, once I write something in the text box, which is not an options of the dropdown, from the next time it will auto include it.
e.g. ->
currently my dropdown is having say three options "Samsung", "Sony", "Apple"
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
Now, "Lenevo" is not available. For the First time in the text box I will write "Lenevo" as my choice, there after it will include it into the dropdown menu.
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
<option value="four">Lenevo</option>
.
.
Like that it will happen.
Thanks for help.. :)
The best solution would be something like select2. (JavaScript)
For examples look here: Link
If you want to stay with PHP only, you need to offer a from to submit text values:
(Disclaimer: This solution is quite bad practice. But it's an example on how to solve it, on a low level.)
1) offer a form
<input type="text" name="addSelection">
2) Read post request
$newOption = $_POST["addSelection"];
3) Persist new option somewhere (here Session, also possible are databases)
$_SESSION["additionalOptions"][] = $newOption;
4) Merge with standard options
$options = ["apple","banana"];
$options = array_merge($options,$_SESSION["additionalOptions"]);
5) Create Options in HTML
<select name="fruits">
<?php
foreach($options as $option){
echo '<option value="'+$option+'">'+$option+'</option>';
}
?>
</select>
Use select2 plugin
https://github.com/select2/select2
<script type="text/javascript" src="/assets/profile/js/select2.min.fda43621.js"></script>
var validateTag = function (term, data) {
var value = term.term;
var re = /^[a-z\d\-_\s]+$/i;
if (re.test(value))) {
return {
id: value,
text: value
};
}
return 'wrong_characters';
};
$("#selectAlt").select2({tags: true, maximumSelectionLength: 6, maximumInputLength: 20, createTag: validateTag});
HTML:
<select name="selectAlt[]" id="selectAlt" multiple="multiple" custom-placeholder="Genre">
<option value="Blues">Blues</option>
<option value="Classic Rock">Classic Rock</option>
<option value="Country">Country</option>
</select>

retain select option values in php

I am unable to figure it out on how to retain select option value after submission. I have looked at various forums and self-help sites:
store drop down options in mysql database, PHP1
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
insert value of html select form into mysql database
Using $_POST to get select option value from HTML
Yet, when refresh the page after selecting the dopwdown options, it wasn't able to retain the last selected value:
Select PHP codes:
$dropdown = elgg_echo('<DIV align="left", >
<form method="post" action="Select.php">
<select name="mycustomFile" >
<option>Select Value..</option>
<option value="A">a</option>
<option value="B">b</option>
<option value="C">c</option>
<option value="D">d</option>
</select>
<p><input type="submit" value="Submit"</p>
</form>
</DIV>');
2nd Code: Select.php (where I perform $_POST[''] action)
<?php
/**
* Override the ElggFile
*/
class FilePluginSelect extends ElggObject {
protected function initializeAttributes() {
parent::initializeAttributes();
$this->attributes['customFile'] = "my_select";
}
public function __construct($guid = null) {
parent::__construct($guid);
}
public function customFile(){
//method to call on model to allow select option
//To post select option into mysql database
$selectOption =$_POST['mycustomFile'];
if(isset($selectOption)){
$sql = "INSERT INTO Entries (mycustomFile) VALUES (".$_POST['selectOption'].")";
}else { // User selected nothing
echo 'No options selected!';
}
}
}
Could someone please help to enlighten me what has gone wrong. Thanks
You're doing it completely wrong. You probably just should use Elgg data model and store your value in metadata unless you have very good reason to ignore framework and do stuff on your own.
First of all don't bother extending ElgObject, you're doing it completely wrong and don't really need it.
To retain selection, you have to read the value and mark tag with selected attribute.
You need to update also action of saving file to include new field value. To save it to metadata you just need to use EAV interface of the entity (you'll find example in http://learn.elgg.org/en/1.12/tutorials/blog.html). Than you can read it within the view you're extending
As for the select element itself, you should use existing input/dropdown view instead. It will save you some boilerplate code. Also no need to add tag as you should be extending existing form view. Views documentation is here: http://learn.elgg.org/en/1.12/guides/views.html
I strongly recommend starting your search in Elgg documentation first. Elgg does have some learning curve, but you want to learn the proper way for your code to be maintainable in future.
set mycustomFile to mycustomFile[] . Also don't post anything into the database without clearing it, its very dangerous.
update:
Your php for getting the value of the select form is correct. Your script isn't working for another reason. Here is a sample of retrieving the select fields data.
<?php
if(isset($_POST['button']))
{
echo 'select value: ' . $_POST['something'];
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="something">
<option value="a">some a</option>
<option value="b">some b</option>
<option value="c">some c</option>
</select>
<button name="button">
click
</button>
</form>
</body>
</html>

PHP Setting select as variable

How can i make piece of select statement as php variable?
Example:
I have 2 options in select statement - edit and delete... I have those 2 options in dropdown menu... I want to make an mySQL query to edit or delete records/users from database...I tried to use switch and cases but it only gave me default as selecting.
<select name="editSelector">
<option name='edit'>Edit</option>
<option name='delete'>Delete</option>
</select>
<?php
if (select == edit)
{
edit query here
}
elseif (select == delete)
{
delete query here
}
?>
I know that this code doesn't have any variables etc. Because i have no idea how to make option as variable. It's connected to database already. Thanks for the answer in advance.
<?php
if($_REQUEST['editSelector'] == "edit"){
edit here;
}
else if ($_REQUEST['editSelector'] == "delete"){
delete here;
}
?>
Plus :
<select name="editSelector">
<option value='edit'>Edit</option>
<option value='delete'>Delete</option>
</select>
you need to place your select > option list in a form and process it the proper way using POST.
I would strongly advise against using ajax to facilitate any crud activity in your database. Unless you know what youre doing its VERY insecure.
heres a reasonable web resource if you need to look things up.
HTML file
<form name='option_form' action='someProcessingFile.php' method='post'>
<select name="editSelector">
<option value='edit'>Edit</option>
<option value='delete'>Delete</option>
</select>
<input type='submit' name='submit' value='Submit'/>
</form>
someProcessingFile.php
<?php
if(isset($_POST['editSelector']) {
switch($_POST['editSelector']) {
case 'edit':
// do something here, probably with the rest of the form
break;
case 'delete':
$id = htmlspecialchars($_POST['id']);
// do something here and delete the entry
break;
default:
// do something here to let yourself know that it all went wrong for some reason.
}
}

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

Categories