php - select option value not passed to post - javascript

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.

Thanks for everyone posting idea's - i've actually got it working, the code was actually working, only error was a misplaced tag, which was placed inside a tag, when placed outside this tag it works ;)

Related

how to retain drop down values as the value selected after submit

My drop down is showing blank then when i select the value of dropdown the same value is showing, but i have to show dropdown value as select first then when I click on button the respective value should show
I am doing a Php program
<form class="form-horizontal" name="form" method="post" action="<?php $_PHP_SELF?>">
<label for="courseDisp" class="col-sm-2" style="margin-top:10px;">Course : </label>
<?php
$course="SELECT * from course";
$res= $conn->query($course);
if($res->num_rows>0)
{
echo '<select name="courseDisp" id="courseDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0" selected> -- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["course_id"].'>'.$row['shortname'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<label for="yearDisp" class="col-sm-2" style="margin-top:10px;">Year : </label>
<?php
$year="SELECT distinct(year) from syllabus";
$res= $conn->query($year);
if($res->num_rows>0)
{
echo '<select name="yearDisp" id="yearDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0">-- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["year"].'>'.$row['year'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<script type="text/javascript">
document.getElementById('courseDisp').value = "<?php echo $_POST['courseDisp'];?>";
document.getElementById('yearDisp').value = "<?php echo $_POST['yearDisp'];?>";
<input type="submit" class="btn col-sm-2" style="margin-left:15px;margin-top:10px;width:60px;font-weight:bold;font-size:15px;" value="GO" name="btnGo" id="btnGo" />
</form>
I think you are doing it in a wrong way:
your code should look like this
<script type="text/JavaScript">
var valueSelected=document.getElementById('course').value;
alert(valueSelected);// do here according to the need
</script>
This is because there is no $_POST variables present before you submit a form.
$_POST variables can only be 'accessed' whenever a POST form is submitted, so when the form is not submitted, $_POST['course'] will be undefined. If you want to use persistant, but also relative variables, use $_GET.
This can be done the following way:
<script type="text/javascript">
document.getElementById('course').value =<?php echo $_GET['course'];?>";
</script>
(this will cause an error if value is not set, make sure to make exceptions for that, using if statements in PHP)
but the value also needs to be fetched from the URL.
so your url needs to have ?course=<course_value> in it, for example:
https://example.com/index.php?course=Course%201
Click here for more about POST vs GET requests
Instead of setting the value with javascript, you should directly write the selected attribute.
<select name="course">
<?php foreach ($options as $key => $value): ?>
<option value="<?= $key ?>"<?php if ($key == $_POST['course']) echo " selected" ?>>
<?= $value ?>
</option>
<?php endforeach; ?>
</select>
If you have to do this in javascript, keep sure, you use the correct syntax. Your example has a wrong " at the end of the line. Also you should use json_encode, if you want to output vars into javascript. And a last thing - if you don't put this inside the document ready event, the script has to be placed after the select element, which you wan't to manipulate
<select name="course">...</select>
...
<script type="text/javascript">
document.getElementById('course').value = <?= echo json_encode($_POST['course']) ?>;
</script>
Needed to keep the <option value="">-Select-</option>

How to fetch multiple dropdowns selected value into a single array using JavaScript

I am trying to fetch values of drop-downs into a node-list having dynamically using a JavaScript. In this code all the drop down have created dynamically and entering the value in a single node-list array. But my query is how to use dynamically. Can anyone suggest me.
please help..
thanks for advance...
<?php
$j=1;
$proQuery=$this->db->query("select * from tbl_subcategory where category_id='$getInv->catg_id' and whr_to_use='for bom'");
foreach($proQuery->result() as $proRow){
?>
<tr>
<th style="width:200px"><?php $techQuery=$this->db->query("select * from tbl_technical_category where sub_catg_id='$proRow->subcategory_id'");
//echo $proRow->subcategory_id;
$i=1;
foreach($techQuery->result() as $techRow){//echo $techRow->techcategory_id;
?>
<select name="tech_prod" id="tech_prod<?=$j."^".$i;?>" class="form-control" required onchange="raptoit(this.id)" <?php if(#$_GET['view']!=''){ ?> disabled="disabled" <?php }?>>
<option value="" selected disabled><?php echo $techRow->tech_catg_name;?></option>
<?php $contQuery=$this->db->query("select * from tbl_technical_product where technical_sub_type='$techRow->techcategory_id'");
$k=1;
foreach($contQuery->result() as $contRow){
?>
<option value="<?php echo $contRow->technical_pro_id; ?>"><?php echo $contRow->tech_pro_name; ?></option>
<?php $k++;} ?>
</select><?php $i++;}?>
<input type="text" id="techId<?=$j;?>" name="techId[]" value="" readonly="" class="form-control">
</th>
</tr>
<?php $j++;}?>
<script>
function raptoit(d){
var zz=document.getElementById(d).id;
//alert(zz);
var myarra = zz.split("^");
var asx= myarra[1];
var asx11= myarra[0];
var value=asx11.split("tech_prod");
var mainId=value[1];
//alert(mainId);
// all select element.
var merge=document.getElementById(asx11+"^"+asx).value;
//alert(dropValue);
// convert nodeList to array
var nodesArray = [].slice.call(document.querySelector("select"));
//alert(nodesArray);
var result = nodesArray.map(select => {return select.value;}).join(',');
alert(result);
document.getElementById("techId"+mainId).value=result;
}
</script>
I have not looked in depth into your code but from a mere glance it seems you are doing it all wrong.
To get the items from the list and parse them on the server side. You should use ajax to communicate between the server and frontend. Look at this https://www.w3schools.com/php/php_ajax_php.asp

select option dropdown onchange update variable

Here is my dilemma. A multi-select drop-down displays pre-selected options. When the user makes any changes, I'm running some code in the PHP action file (called through a submit button). I'm trying to accomplish this using a flag and updating the flag in the onchange event of "select option". The rest is working fine. I just wanted to execute the queries in action file only when the user changed selections in drop down rather than every time the form is submitted. However I'm unable to pass the flag successfully. I know I'm missing something basic and have spent two days looking at it. Any help is appreciated.
The relevant code is pasted below:
//Initialize flag
<?php
...
$multi_prog_change_flag = '0';
...
?>
//Hidden Form Element
<form action="update_u.php" method="post" id="cForm" name="cForm" onsubmit="return validateForm()" autocomplete="off">
...
<?php echo '<input type="hidden" id="email" value="'.$email.'"> ';?>
<?php echo '<input type="hidden" id="multiprogchangeflag" name="multiprogchangeflag" value="'.$multi_prog_change_flag.'"> ';?>
...
// Drop-down Element where update is triggered
<tr id="odd">
<td><select id="programName" name="programName[]" onchange="updateflag();>" multiple="multiple" size=10>
..
<option name="drop1" value ="<?php echo $data['Program_Id'] ?>" <?php if ($data[curr_prog] == '1') echo 'selected="selected"'; ?>> <?php echo $data['Program_Name'];?></option>
..
</select>
<input type="hidden" id="pNames" name="pNames" value="" />
</td>
</tr>
// Function to update flag
function updateflag() {
<document.getElementById("multiprogchangeflag").value = "1";
}
// update_u.php PHP Action File
$multi_prog_flag=mysql_real_escape_string($_POST['multiprogchangeflag']);
if ($multi_prog_flag == '1'){
$multi_prog_delete_query=mysql_query("UPDATE multi_prog_access SET is_act = '0', Updated_by = '$updatedby', update_timestamp = NOW() WHERE user_id = '$useid'");
$count = count($multi_prog_names);
for($i=0;$i<$count;$i++){
$multi_prog_ID=$multi_prog_names[$i];
$multi_prog_update_query=mysql_query("INSERT INTO multi_prog_access (user_id, Prog_id, created_by, is_act, Update_timestamp) VALUES ('$ids','$multi_prog_ID', '$updatedby', '1', NOW())");
}
}

How to put seach box inside in a dropbox?

I have problem how to put seach box inside in a dropbox, I had already a code using some javascript but It didn't work can you please help me about it?
Here's my code
<script type="text/javascript">
$(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>
here's my select tag codes:
<?php
$sql = mysql_query("SELECT * FROM barangay");
?>
<select class="js-example-basic-single" name="barangay_ID" style='width:160px;height:38px;border-radius:8px;border-color:#D7D7D7;margin-left:55px;' autofocus required>
<option disabled selected hidden>← Please select →</option>
<?php
while ($row = mysql_fetch_array($sql)){
echo "<option value='".$row['barangay_ID']."'>".$row['barangay_name']."</option>";
}
echo "</select>";
?>
Don't know why it doesn't work please help mean example

How to make HTML form fields automatically change when an option selected on a select field

Let's say I have a form like this in my CodeIgniter project.
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" name="S_happened">
<?php echo form_close(); ?>
What I want to do is if an user select one status, according to the it's type, show a text field to get an input.
I've made a way to get a type of the status like this: http://localhost/myapp/index.php/status/type/{status_id} where users can pass status ID and it will "echo" the type of the status.
I want to receive it back to the HTML page via a JavaScript method and show those text input fields. How do I do that?
Thank you. :)
As you have jQuery tag, so i suggest you this:
$('select').change(function(){
var inp = this.value.trim();
$(this).parent().find('input[type="text"][name^="'+inp+'"]').show().siblings(':text').hide();
});
I have posted the sample flow as per you want to do. hope this will helpful for you.
PHP:
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" id="E_happened" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" id="S_happened" name="S_happened">
<?php echo form_close(); ?>
JAVASCRIPT :
$('select').change(function(){
var statusId = $(this).val();
var statusType = $.get("http://localhost/myapp/index.php/status/type/"+statusId);
if(statusType == 'E')
{
$('#E_happened').value("what do you want here");
}
if(statusType == 'S')
{
$('#S_happened').value("what do you want here");
}
});

Categories