Problem with keeping selected value in form after reloading page - php

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.

I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Related

Update Cookie via HTML select element

I want to built a "currency-changer" for a website. Right now, I am setting a cookie via PHP. The name is "Currency", the value is "USD".
So if a user enters the site, this cookie is set.
if(!isset($_COOKIE['Currency'])) {
setcookie('Currency', 'USD' ,time()+31536000, '/', '.domain.com');
$_COOKIE['Currency'] = 'USD';
}
What I now want to achieve is, that the cookie can be updated via an HTLM select-list.
<form>
<select id="setcurrency" name="setcurrency" />
<option value="USD">USD</option>
<option value="GBP">GBP</option>
<option value="EUR">EUR</option>
</form>
How could I do it the best way, so that the cookie is updated and then the page is reloaded. All this needs to be done in PHP. I could do it in JQuery, but PHP is a must and I am a noob :(
Thank you very much in advance!
If you want to use jQuery with PHP then you can try this:
jQuery:
<script type="text/javascript">
$("#setcurrency").change(function(){
$("#formID").submit(); // you need to add form id and form method
});
</script>
PHP:
if(isset($_POST['setcurrency'])) {
setcookie('Currency', $_POST['setcurrency'] ,time()+31536000, '/', '.domain.com');
}
in jQuery, first of all you need to add id="formID" on your form with method="post" and make sure jQuery library included in your code.
In my jQuery example, i am just submitting the form on dropdown selection.
Then you can overwrite the existing cookie value by using PHP.
How about having an iframe with a blank html file, with the iframe having a name, and the form targets the iframe with a post/get action to a php file and then in that php file you update the cookie?
Of course, then the parent page that is posting/getting the form data will need a refresh or reload to read that cookie

Finding and replacing PHP Variable value from user drop down box

Is it possible in PHP to find and replace a PHP variable with a user defined value from a drop down box on a different PHP page.
Example:
PHP Page 1
$test = '1234';
PHP Page 2
Drop Down Values: (Find and replace $test variable with Drop Down selection)
1
2
3
4
Im have not found much information about this.
The purpose is to pass hexadecimal colours based on user choice.
PHP Variables are server-side variables. You can not change server side variables from client side directly.
Common approaches are: (Although both do same in background)
Using GET to send your data
Using AJAX to dynamically send, fetch and change DOM (Maybe preferred in our case)
On selecting the item on the Drop Down menu, you need to call a method which sends a data to your PHP page and you can change variables.
Your PHP page should handle a GET request change the variable to $test
$test = $_GET["sent_variable"]
While on AJAX, you need to something like:
$.ajax({
url: "your-php-page.php",
type: "POST",
data: { sent_variable: selectedVar}
}).done(function() {
//Something here after doing
});
Read more about AJAX here.
Note: You have to trigger AJAX on selecting drop-down menu. Read about that here.
Assuming the dropdown box is part of a form, you can use the 'post' method.
e.g.
<!--HTML-->
<form method="post" action="myScript.PHP">
<select name="myOption">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="GO">
</form>
//myScript.php file
<?PHP
$test = $_POST['myOption'];
echo $test;
?>
I actually have a page on my own site that uses similar functionality for passing hex colours if you want to have a look at the HTML source code http://www.wxls.co.uk/formatmyvba.html

Drop down live update in a form

How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?
Would appreciate any code examples to work from.
Many thanks!
You are going to have to use AJAX, I would recommend jQuery's abstraction.
e.g.
<select id="sel1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
$.ajax({url: 'fetchSel2.php',
data:{sel1:$('#sel1').val()},
success:function(data){
$('#sel2').html(data);
}
});
});
</script>
This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.
e.g.
function getSecondOptions($sel1){
$r=mysql_query(RELEVANT_QUERY);
$opts='';
if($r && mysql_num_rows($r)>0){
while(list($label,$val)=mysql_fetch_row($r)){
$opts.='<option value="'.$val.'">'.$label.'</option>';
}
}
return $opts;
}
if(isset($_GET['sel1'])){
echo getSecondOptions($_GET['sel1']);
}
exit;
For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.
What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.
I recently did this with jQuery http://jsfiddle.net/tBrXt/1/
You have these options:
Use AJAX if you don't want the form to refresh and update parts of
the form.
If you don't want to use ajax and can bear with refreshing the whole
form, you can capture the onChange event of the drop down using
javascript.
If the user does not have javascript enabled, the above 2 methods
will fail. Therefore, it is best to include a button users can click,
which will ask the PHP side to rerender the form.
My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.

Clearing a selected item from a dropdown using PHP

I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to onclick() and receive the event on the server side, then you will need to use an AJAX call. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.
you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html
use jquery
jquery auto suggestion

Autofill form when link is pressed

I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)

Categories