Am a php novice and in need of some help. Basically I have a script that populates a drop down select bar using php. I want to retain the value the user selects in this drop down after submission, so the user does not have to select it again, here is the snippet of the script that I am trying to work with.
<?php
// Start the session
session_start();
$_SESSION["dir"] = $_POST['hiddenVal'];
//echo "hi at last" .$_SESSION["dir"];
?>
<script>
function loadValues()
{
var $x=obj.options[obj.selectedIndex].value;
document.getElementById("hiddenVal").value = $x;
//alert(document.getElementById("hiddenVal").value);
}
</script>
<script>
function country(obj){
//alert(obj.options[obj.selectedIndex].value); //if you want to show in alart
//or put in a variable
var $x=obj.options[obj.selectedIndex].value;
document.getElementById("hiddenVal").value = $x;
alert($x);
}
</script>
<body onload="loadValues();">
<form action="dir20.php" method="post">
<input type="hidden" id="hiddenVal" name = "hiddenVal"/>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
<?php
$path = '/docdownloads';
//echo 'php_'.$abc;
$dirs = array();
// directory handle
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
if ($entry != '.' && $entry != '..') {
if (is_dir($path . '/' .$entry)) {
$dirs[] = $entry;
//echo "$entry</br>";
}
}
}
?>
<select name="country" id="country" onChange="country(this)" required>
<!--<option value="">-----------------</option>-->
<?php
asort($dirs);
reset($dirs);
foreach($dirs as $p => $w):
echo '<option value="'.$w.'">'.$w.'</option>'; //close your tags!!
endforeach;
?>
</select>
<?php
$tex = $_SESSION["dir"];
//$def = "docdownloads";
//$dir = "c:/".$tex;
$dir = "c:/docdownloads/".$tex;
//echo "tex is". "$dir";
echo "</br>";
//if ($handle = opendir('.')) {
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry</br>";
}
}
closedir($handle);
}
?>
You're going to want to check the $_GET var against the selected option. If the current option exists and it has been selected, then give the option the selected attribute.
-----------------
<?php
asort($dirs);
reset($dirs);
foreach($dirs as $p => $w):
$selected = isset($_GET['country']) && $_GET['country'] === $w ? "selected" : "";
echo '<option value="'.$w.'"'.$selected.'>'.$w.'</option>';
endforeach;
?>
</select>
You will need to assign a ID for user if you havent already, then save the submitted option in your database with corresponding ID. Then when you load you'r dropdown box insert a IF clause in your script to check if user has already saved a option.
To achieve that you should save the value the user chose into session
and always when displaying the form, you should check if the value exists in the session and if it exists - display it as selected option.
get the submitted value of country by GET or POST(depend on your form method) and compare it in foreach loop
$countryId = isset($_POST['country']) ? $_POST['country'] : ''; //or $_GET['country'];
foreach($dirs as $p => $w):
$selected = $countryId==$w ? 'selected' : '';
echo '<option value="'.$w.'" '.$selected.'>'.$w.'</option>';
endforeach;
Assuming your form action is on same page, if different, store country value in session and retrieve it from session in this page
Blockquote You need to put your select element inside your form. Otherwise it won't submit
problem solved, script now works, many thanks!
Related
I want to return the contents of a folder as a radio button. I would like to be able to return the selected option in a variable so that I can then show the user what they have selected.
How do I solve this problem?
Attempt
$dir = '/beta/import/';
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo ("<form action=\"#\" method=\"post\">");
foreach ($files as $file) {
echo '<input type="radio" name="files[]" value="' . $file . '" /> ' . $file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' . '</form>';
echo "<br>";
if (isset($_POST['submit'])) {
$selected_val = $_POST['$file'];
echo "You have selected :" . $selected_val;
}
} else {
exit('No files found.');
}
Since you use name="files[]", $_POST['files'] will be an array, not a single value. There's little point in doing this for radio buttons, since you can only select one of them, and the array will always have one entry. So you should change that to name="file".
If you make that change, your code to print the selection should work.
You also need to remove action="#" from the form. That prevents the form from submitting, so you'll never get any $_POST variables (unless you submit the form using AJAX).
I have a drop down list that generates all files in a folder, which is working. But i would like to only see .jpg files and also i would like to exclude one file from the list as it is a place holder image lets call it "0001_Place_Holder.jpg".
The second part to this is that i want to pick a file from the dropdown list and copy it to a New folder then delete the original image.
this is "move_files_general.php" // which generates my dropdown list
<?php
$dirname = "general_2";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality" class="submit" />';
echo '</form>';
?>
This is "move_general.php" // which should copy the file then delete the original
<?php
$dirpath = "general_2";
$dirpath_2 = "quality_2";
$file_to_move = $_GET['file2'];
copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move") or die("Unable to copy");
if (copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move")) {
unlink("$dirpath.'/'.$file_to_move");
if ( unlink ($dirpath.'/'.$file_to_move) ) {
echo $file_to_move . " deleted.";
echo '<script>parent.window.location.reload(true);</script>';
} else {
echo "Error.";
}
}
?>
You would test the filename if its extension is jpg and if it is not equal to your placeholder name.
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
For the second issue: try to set the folder permissions to 777 for testing purpose. Also echo the strings that you pass to copy(string1,string2) in order to check if something is wrong in there.
First off, Thanks for your answers, and help. Alex Odenthal, that worked for the 1st part. i tried everything to get the 2nd part to work. I finally rewrote it a different way and it's working now, I must have had something wrong , somewhere.
Here is my fixed "move_files_general.php"
<?php
$dirname = "general";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder_DO_NOT_DELETE.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality1" class="submit" />';
echo '</form>';
?>
Here is my fixed "move_general.php"
<?php
$file_to_move = $_GET['file2'];
$source = "general/$file_to_move";
$dest = "quality/$file_to_move";
copy($source, $dest);
if (copy($source, $dest)) {
unlink($source);
if(file_exists($source)) {
unlink($source); }
else {
echo "Deleted.";
}
}
?>
I have a dropdown control which and I would like it to default to a specific option based on the access of the logged in user. For example, the dropdown has 10 options but only administrators have access to view all 10 options. The majority of users only have access to 1 of the options though. The page contents are hidden/displayed based on whether or not the value of the dropdown is null.
Question: Using the example above, if an admin is logged in I need the dropdown to default to "Select an option". This way the page content is hidden. On the other hand, if a user with access to only 1 is logged in, I need it to default to that 1. This way they don't have to select anything and, by default the page content is displayed. How do I go about doing this?
Below is my current code which handles what the dropdown displays based on when a selection is made.
PHP/HTML
// Hide/Show main content div
<?php
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) { // If value is null, default to 'Select an option'
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
while ($row = odbc_fetch_array($db)) {
echo "<option value=\"".$row['content']."\">".$row['content']."</option>";
}
} else { // If value not null keep the selected value selected
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
// Pass selected value on change
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
SQL
// Hardcoding user for testing purposes, THIS WILL BE CHANGED
function getOptions() {
$results = "SELECT content, userid FROM table WHERE userid = 'username'";
return $results;
}
Any help is much appreciated and please let me know if I'm not clear about anything.
Got some help and have it figured out now. Here is the revised code:
PHP/HTML
// Hide/Show main content div
<?php
$src = null;
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) {
$i = 0;
$content = "";
while ($row = odbc_fetch_array($db)) {
$content .= "<option value=\"".$row['content']."\">".$row['content']."</option>";
$i++;
}
if ($i > 1) {
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
}
echo $content;
if ($i > 1) { $oneopt = 1; }
else { $oneopt = 0; }
} else {
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
<?php
global $optone;
if ($optone == 1) {
echo "$('#select1').trigger('change');";
}
?>
SQL -- Stays the same
#chenasraf really appreciate the help! Hope this can be of some help to someone in the future!
The preselected option is always the first to have a "selected" attribute. Your first disabled one has it first on all cases, so it's always chosen. Remove that and work from there.
On a side note, I think you can manage to make this options part work better. I've taken the liberty of rewriting it for you:
<select name="select1" id="select1">
<?php
$selected = '';
while ($row = obdc_fetch_array($db)) {
$options[] = '<option value="'.$row['content'].'">'.$row['content'].'</option>';
if ($row['content'] == $src)
$selected = count($options) - 1;
}
array_unshift($options, '<option disabled="disabled"', $selected == '' ? ' selected="selected"' : '','>--Select an option--</option>');
foreach ($options as $option) {
echo $option;
}
?>
</select>
Did my best to not post this question but i just can not figure this one out. I'm trying to pass a variable from my html form to a php script the code looks like this so far
<?PHP
echo "<b>Previously Submitted</b><br />";
echo "<select name='files' onChange='updateInfo();'>";
echo "<option value=''></option>";
$files = scandir("businesses");
foreach ($files as $file)
if($file != "."){
if($file != ".."){
if($file != "form.php"){
echo "<option value='$file'>". htmlspecialchars($file) ."</option>";
}
}
}
echo "</select>";
?>
<script type="text/javascript">
function updateInfo(){
<?PHP
mysql_connect("HOSTHERE","USERNAME","PASSWORD");
mysql_select_db("USERNAME");
//This is the line that is of interest i can't figure how to pass document.forms['frm'].files.value to my query
$bizname = mysql_query("SELECT `Value` FROM `" . document.forms['frm'].files.value . "` WHERE `Variable` LIKE 'Name'");
$bizValue = mysql_fetch_assoc($bizname);
echo "document.forms['frm'].businessname.value = '" . $bizValue['Value'] . "';";
mysql_close();
?>
}
</script>
Any help would be greatly appreciated on how i can pass a value from my drop down to the php code.
EDIT
Just to clear things up on what i'm doing sorry about some confusion basically i have a dropdown menu and when the dropdown menu is changed i want to query my database using whatever is in the dropdown as the table in the query and then what ever the value i get from the database is set in my form in a text field. It's all in one page and just trying to update the text filed when the dropdown is changed
The way you have written updateInfo script is not possible. using php concatenation (i.e ".") you can concatenate only php variables not java-script. PHP does not understand it.
what i suggest you is to use ajax. In your updateInfo pass the changed value.
<?php
echo "<select name='files' onChange='updateInfo(this.value);'>";
echo "<option value=''></option>";
$files = scandir("business");
foreach ($files as $file)
if($file != "."){
if($file != ".."){
if($file != "form.php"){
echo "<option value='$file'>". htmlspecialchars($file) ."</option>";
}
}
}
echo "</select>";
?>
and then send ajax and get response. and treat response as you want
<script type="text/javascript">
function updateInfo(val){
$.ajax({
url: '/path/to/ajaxrequest.php',
type: 'post',
data: {'file':val}
success: function(response){
document.forms['frm'].businessname.value = response;
}
});
</script>
and your ajaxrequest.php
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest'){
mysql_connect("HOSTHERE","USERNAME","PASSWORD");
mysql_select_db("USERNAME");
$file = mysql_real_escape_string($_POST['file']);
$bizname = mysql_query("SELECT `Value` FROM ".$file." WHERE `Variable` LIKE 'Name'");
$bizValue = mysql_fetch_assoc($bizname);
$assignVal = $bizValue['Value'];
mysql_close();
echo $assignVal;
}
?>
if you don't get this let me know. thank you.
here i am giving you a link to download code
Put tag inside the HTML Form element..Also I have not understood why you are merging javascript and PHP mysql update function.
yo can write code like
1.Form Element with
Done.
you need to submit the form. you can use post or get as method. but without submitting you can not pass variable from html to php.
<?PHP
echo "<form name='frm_1' id='frm_1' action='your_destination_page.php' method='post>'";
echo "<b>Previously Submitted</b><br />";
echo "<select name='files' onChange='updateInfo();'>";
echo "<option value=''></option>";
$files = scandir("businesses");
foreach ($files as $file)
if($file != "."){
if($file != ".."){
if($file != "form.php"){
echo "<option value='$file'>". htmlspecialchars($file) ."</option>";
}
}
}
echo "</select></form>";
?>
on destination page write this on the top of the page
<?php echo "<pre>";print_r($_POST);echo "</pre>";?>
you will have values of all controls in $_POST array.
<?PHP
echo "<b>Previously Submitted</b><br />";
echo "<select name='files' onChange='updateInfo();'>";
echo "<option value=''></option>";
$files = scandir("businesses");
foreach ($files as $file)
if($file != "."){
if($file != ".."){
if($file != "form.php"){
echo "<option value='$file'>". htmlspecialchars($file) ."</option>";
}
}
}
echo "</select>";
?>
<script type="text/javascript">
function updateInfo(){
<?PHP
mysql_connect("HOSTHERE","USERNAME","PASSWORD");
mysql_select_db("USERNAME");
//This is the line that is of interest i can't figure how to pass document.forms['frm'].files.value to my query
$bizname = mysql_query("SELECT `Value` FROM `" . document.forms['frm'].files.value . "` WHERE `Variable` LIKE 'Name'");
$bizValue = mysql_fetch_assoc($bizname);
$assignVal = $bizValue['Value'];
echo "<script>document.forms['frm'].businessname.value = '" .$assignVal . "';</script>";
mysql_close();
?>
}
Try enclosing in a script tag.
I have a select box that shows 3 options: option1, option2, option3. When a user hits submit, then in $_POST I do have the value selected. Is there an easy way to redisplay the select box with the chosen option highlighted WITHOUT it being repeated in the options?
In other words, if option2 is selected and submit is clicked, the page should display again with option2 selected, and option1 and option 3 underneath.
Thanks.
<?php
$arrValues = array(...);
$selectedValue = (isset ($_POST['selectName']) ? $_POST['selectName'] : "");
?>
<select name="selectName">
<?php
for ($i = 0; $i < count($arrValues); $i++)
{
$opts = ($arrValues[$i] == $selectedValue) ? ' selected="selected"': '';
echo '<option value="' . $arrValues[$i] . '"' . $opts . '>' . $arrValues[$i] . '</option>';
}
?>
</select>
Create your options like this.
$options = array("optionvalue" => "Option Name");
foreach($options as $value => $name)
{
if(isset($_POST['select_box']))
{
if($_POST['select_box'] == $value)
{
echo '<option selected="selected" value="'.$value.'">'.$name.'</option>';
continue;
}
}
echo '<option value="'.$value.'">'.$name.'</option>';
}
When you generate the select box, use the POST data (if available) to pick the item that's selected (and/or to sort the items).
Kind of like:
if($_POST["optval"] == $opt) $sel = "selected='selected'"; else $sel = "";
print "<option value='$opt' " . $sel . ">$opt</option>";
Naturally you'd want to verify that the POST data is valid and that it exists (isset). Assuming of course that you generate your select box from data accessible by PHP, rather than statically define it.