简体   繁体   中英

php - select option value not passed to post

Im pretty stuck at this code, I really can't see why it should not work, i don't know if some javascript code im running beforehand is interfering?

Only showing relevant part of the code

The first section with javascript updates page when selecting another dropdown, and is placed before the code that im struggling with: `

<script type="text/JavaScript">

function changeDropDown(){
   var elLocation = document.getElementById('form_location_id');
   var location = elLocation.options[elLocation.selectedIndex].value;

     document.getElementById("form1").action = "choose.php?id=" + location;
     document.getElementById("form1").submit();
   }

</script>

<form id="form1" name="form1"  method="post">
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>

<?php
if ($chosen_id == "1") { ?>
<option value = "1" selected><?php echo "dropdown text" ?></option>
<? } else { ?> 
<option value = "1"><?php echo "dropdown text" ?></option>
<?php } ?>

</select>
</form>

<form method="post" action="update.php">
<select size="1" id="choice" name="value">

<?php
while($row = mysqli_fetch_array($query)) {

$id = $row['id'];
$number = $row['number'];
>?    
<option value = "<?php echo ($id) ?>"><?php echo "ID=" . ($id) . " - #" . ($number) . ""?></option>

<?php
}
mysqli_close($db_conn);

?>
</select>

<input name="submit" type="submit" value="Submit">
</form>

update.php:

<?php
if (isset($_POST['submit'])) {
$chosen_id = $_POST['id']; 
}
?>
`

I've only posted the code handling the select option and the post part...

Why is the $chosen_id variable always 0 ? The while loop works, and fill's the variable, as this is tested with echo command inside the option line

Any help is much appreciated...

$_POST['id'] and <select size="1" id="choice" name="value">

Use $_POST['value']

You are trying to print the wrong key if you trying to get the value of form_location_id

$chosen_id = $_POST['form_location_id']; 

And if you trying to get the value of choice

$chosen_id = $_POST['value']; 

This is why when you post a form to php it use html name attribute as key to assign the value to $_POST Array

I'd change Update.php to

<?php
if (isset($_POST['value'])) {
$chosen_id = $_POST['value']; 
}
?>

You need to use the form_location_id to get the required value. You are using the wrong key to access the data. You need to use the name of the input. In this case, the input is the select and the name of that is form_location_id . So, you need to do this.

$value = $_POST['form_location_id']; 

Try it out and do let me know if it worked out for you.

感谢大家发布想法-我实际上已经使它起作用,代码实际上正在起作用,唯一的错误是放错了标签,该标签放置在标签内,而放置在该标签外则有效;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM