reload PHP variable as submitted in dropdown menu via AJAX - javascript

On a webpage I am trying to create a dropdown menu with some features. After a selection has been made in the dropdown menu the PHP variable "$bin_sec" gets updated to a new value. After $bin_sec has been updated I want a div element (with the id tag of "WHAT") in my webpage to now be reloaded and now take on the new value of $bin_sec.
I'm open to using AJAX, PHP, jQuery, MySQL, etc...
I can't find or come to a working solution.
My code for the dropdown menu:
<form id="container2" method="post">
<select name="name" onchange='$("#WHAT").load("testing.php",{bin_sec:x});'>
<?php $bin_sec=60;?>
<option selected="selected" <?php if ($_POST['name'] == '60'){ print 'selected'; $bin_sec=60; }?> value="60">1 Minute</option>
<option <?php if ($_POST['name'] == '120'){ print 'selected'; $bin_sec=120; }?> value="120">2 Minutes</option>
<option <?php if ($_POST['name'] == '300'){ print 'selected'; $bin_sec=300; }?> value="300">5 Minutes</option>
<option <?php if ($_POST['name'] == '600'){ print 'selected'; $bin_sec=600; }?> value="600">10 Minutes</option>
</select>
</form>
<div id="WHAT">
<?php
echo $bin_sec;
...
?>
</div>
testing.php:
<?php
$bin_sec = $_POST['name'];
?>
<script type="text/javascript">
$("#WHAT").load("index.php #WHAT")
</script>
I think this code should work but it doesn't...
Any corrections would be very much appreciated. Thank you in advance.

There are Many Ways to do it one sample way is given below
<?php
if(isset($_GET['bin_sec']))
{
$bin_sec=$_GET['bin_sec'];
}
else
{
$bin_sec=60;
}
?>
<select name="bin" onchange="window.location.href='stack.php?bin_sec='+this.value">
<option <?php if($bin_sec == '60'){ print 'selected';}?> value="60">1 Minute</option>
<option <?php if ($bin_sec == '120'){ print 'selected'; }?> value="120">2 Minutes</option>
<option <?php if ($bin_sec == '300'){ print 'selected'; }?> value="300">5 Minutes</option>
<option <?php if ($bin_sec == '600'){ print 'selected'; }?> value="600">10 Minutes</option>
</select>
<div id="WHAT">
<?php
echo $bin_sec;
?>
</div>
I hope it helps and stack.php is your php file where dropdown exists i hope you understand for any doubts revert back

You will need to echo out $bin_sec in PHP in order for it to be sent to the browser.
Additionally you need to change your $_POST var to the same name as you are sending from the browser as $_POST['name'] does is undefined
Example below
<?php
$bin_sec = $_POST['bin_sec'];
echo $bin_sec;
?>

You can use this code:
<option <?php if ($_POST['name'] == '120'){ print 'selected'; =120; }?> value=" <?php $_POST['name'] == '120'? "$bin_sec_value":120 ; ?>">2 Minutes</option>

Related

How to hide select options when there is no data

I'm building a drop-down list with options containing data from a database and want to hide options which have zero data.
I have tried an if statement using continue but failing to catch the live data values from the database.
<select name='Database' title="Choose from database">
<option value="">All</option>
<?php foreach($database as $row):
if ($row['topic'] == 0) {
continue;
}
else {
?>
<option value="<?= $row['topic']; ?>"
<?php if ($row['topic'] == $_SESSION['prosess']){echo "
selected";}?>>
<?= $row['topic']; ?>
<?php }?>
</option>
<?php endforeach; ?>
</select>
Is there any clever javascript-, php-, etc. code that can deactivate/hide options from a database which are empty.
Add this in your css:
select option:empty {
display:none
}
I think you should try this.
<select name='Database' title="Choose from database">
<option value="">All</option>
<?php
if(count($database) > 0)
{
foreach($database as $row)
{
?>
<option value="<?= $row['topic']; ?>"
<?php if ($row['topic'] == $_SESSION['prosess']){echo "
selected";}?>>
<?= $row['topic']; ?>
<?php }?>
</option>
<?php
}
}
?>
</select>
Hope it helpful for you.

how to avoid repetition of values in dropdown list while updating in php

I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>

Keep the selected options after submitting the form

Good morning, I have a problem that is: I can not keep several options selected after submitting the form and I would like someone to help me.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>"><?php echo $reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>
this is my code to have the various options in the select box
You have to check if $_POST['utilizadores'] or $_GET['utilizadores'] it depends on your request type. I will use $_POST in here for explain my answer.
your select is multiple, you can use in_array function for checking that if result from db record is in array of $_POST['utilizadores']
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
**<option value="<?php echo $reg_sql['ID_USER']; ?>"
<?php
if(isset($_POST['utilizadores'])){
if(in_array($reg_sql['ID_USER'], $_POST['utilizadores'])){
echo 'selected';
}else{
echo '';
}
}
?>
>**<?php echo
$reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
You may be able to do it more efficiently if your database result also contains which rows are selected, but when you loop through, just add the selected="selected" attribute to the <option> tag.
Assuming your $_POST array exists in this scope, you can use the in_array function in PHP to determine if the option has been selected (docs).
The ternary based operation is as follows:
in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : ''
Which says "if the ID_USER is in the post array, then print the selected attribute, otherwise, print a blank string"
Putting it all together:
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>" <?= in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : '' $?>>
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
An example of how you can do this. Either add the "selected" string if yes or leave blank if no. You can also write selected="selected". You can do the same thing to set disabled or readonly.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<?php $selected = isset($reg_sql["mi_variable"]) ? "selected" : ""; ?>
<option value="<?php echo $reg_sql['ID_USER'];?>" <?php echo $selected; ?> >
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>

How to change a second select list based on the first select list option when values are dynamic?

I have php page for vehicle search filter which have 2 types of vehicle that is RV's and campervans and also have two selects
<div class="fields">
<p>Vehicle Type</p>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<?php if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){ ?>
<option value="<?php echo $vt ?>" <?=isset($_GET['car_type'])&&$_GET['car_type']==$vt?'selected':'';?> ><?php echo $vt ?></option>
<?php }
} ?>
</select>
</div>
<div class="fields">
<p>Total No. of Passengers*</p>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<option <?php if(#$_REQUEST['passengers'] == 1){?>selected<?php }?>>1</option>
<option <?php if(#$_REQUEST['passengers'] == 2){?>selected<?php }?>>2</option>
<option <?php if(#$_REQUEST['passengers'] == 3){?>selected<?php } ?>>3</option>
<option <?php if(#$_REQUEST['passengers'] == 4){?>selected<?php }?>>4</option>
<option <?php if(#$_REQUEST['passengers'] == 5){?>selected<?php }?>>5</option>
<option <?php if(#$_REQUEST['passengers'] == 6){?>selected<?php }?>>6</option>
<option <?php if(#$_REQUEST['passengers'] == 7){?>selected<?php }?>>7</option>
<option <?php if(#$_REQUEST['passengers'] == 8){?>selected<?php }?>>8</option>
</select>
</div>
How do I do that with jQuery or php if I choose "Rv" in the first select? The second select would show me 8 passengers . If I choose Campervan in the first select, the second select would show me 5 passengers..
I would probably do something along these lines:
<?php
$number_of_passengers = 8;
if(!empty($_REQUEST['car_type'])) {
$number_of_passengers = $_REQUEST['car_type'] == 'Campervans' ? 5 : 8;
}
$passengers = 0;
if(!empty($_REQUEST['passengers'])){
$passengers = (int) $_REQUEST['passengers'];
}
?>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<option value="RV/Motorhome">RV/Motorhome</option>
<option value="Campervans">Campervans</option>
</select>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<?php
for($i = 1; $i <= $number_of_passengers; $i++) {
?>
<option
<?php
if($i == $passengers) {
echo ' selected ';
}
?>
>
<?php echo $i ?>
</option>
<?php
}
?>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#car_type').change(function() {
$("#passengers").children().removeAttr("selected");
if ($(this).val() === 'Campervans') {
$('#passengers option:nth-child(n+7)').hide();
} else {
$('#passengers option').show();
}
});
</script>
There are cleaner ways of doing this but this should serve to get the point across.
Few things to note about the PHP:
See how I check if the $_REQUEST key is available using empty - this avoids having to use # which is generally not a good idea.
I am using a loop to echo the options in the passenger select to avoid code repetition because typing that out 8 times is boring ;-)
Hope this helps!
yes you need to add javascript code for that.
insert below code in your page and check if this is what you want?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$('.car').on('change', function(){
if($(this).val() === 'RV/Motorhome'){
$('.half').find('option').show()
}else if($(this).val() === 'Campervans'){
$('.half').find('option').slice(6).hide();
}
})
</script>

Is Javascript causing my form to not echo selected once error reloads the page?

I am still new at PHP/Javascript/Ajax and am having a very hard time (been going on for weeks) troubleshooting this problem.
My site has a registration to be a member page that requires all fields to be filled out. This is a website for the Cystic Fibrosis community, so there is a section on the form where you choose your relationship to Cystic Fibrosis. (I have it/ Someone I know has it) If you choose I have it, a drop-down box appears and gives you the option Fibro(male) or Cyster(female). If you choose someone I know, a different drop-down opens with various options(aunt, uncle etc.)
I have a myriad of possible errors that can be made. Passwords don't match, captcha or terms of use not checked/filled out, etc...therefore the page reloads to display the error message. I have put "echo selected" in all of my option values to have the page load the previously selected information as it should. When you choose 'I have CF' this is what happens:
When signing up - if I select "I have CF" the first time but forget to fill in "Cyster or Fibro" I get the error message. THEN when I go back and add in Cyster or Fibro, it continues to tell me, that I need to enter my relation to CF, even though it SHOWS in the box that Cyster or Fibro is selected.
If I'm signing up. Have filled in the relation to CF as "I have CF" AND filled in the "Cyster or Fibro" but get ANY error message (wrong email, passwords don't match etc) the Cyster or Fibro answer falls out (not there) and if I select it again, it will not accept my choice and keeps saying that "you must choose your relation" even though it's clearly been selected.
Like I said, I've been struggling with this for weeks, and as far as I can tell my code looks correct. I'm thinking it has something to do with the Javascript? Here is my code:
(Please let me know if you need surrounding code to help, thank you)
<tr>
<td class="left">
<span style="color:#FF0000;">*</span> Relation to CF:
</td>
<td class="right">
<select name="CFDistance" onchange="switch_distance(this);">
<option value="null" disabled selected>choose one</option>
<option value="self" <?php if($_POST['CFDistance'] == "self") { echo "selected"; } ?>>I have CF</option>
<option value="others" <?php if($_POST['CFDistance'] == "others") { echo "selected"; } ?>>Someone I know has CF</option>
</select>
<div id="self_cf_box" class="signup_dropdowns" style="margin:10px 0px 0px 0px;<?php if($_POST['CFDistance'] != "self") { echo "display:none;"; } ?>">
<span style="color:#FF0000;">*</span> I am a
<select id="RelationToCF_self" name="RelationToCF" <?php if($_POST['CFDistance'] != "self") { echo "display:none;"; } ?>>
<option value="null" disabled selected>choose one</option>
<option value="Fibro" <?php if($_POST['RelationToCF'] == "Fibro") { echo "selected"; } ?>>Fibro (male)</option>
<option value="Cyster" <?php if ($_POST['RelationToCF'] == "Cyster") { echo "selected";} ?>>Cyster (female)</option>
</select>
</div>
Here is the other option (I know someon with CF) that is working just fine:
<div id="others_cf_box" class="signup_dropdowns" style="margin:10px 0px 0px 0px;<?php if($_POST['CFDistance'] != "others") { echo "display:none;"; } ?>">
<span style="color:#FF0000;">*</span> I am this person's
<select id="RelationToCF_others" name="RelationToCF" <?php if($_POST['CFDistance'] != "others") { echo "display:none;"; } ?>>
<option value="null" disabled selected>choose one</option>
<option value="Mom" <?php if ($_POST['RelationToCF'] == "Mom") { echo "selected"; } ?>>Mom</option>
<option value="Dad" <?php if ($_POST['RelationToCF'] == "Dad") { echo "selected"; } ?>>Dad</option>
<option value="Aunt" <?php if ($_POST['RelationToCF'] == "Aunt") { echo "selected"; } ?>>Aunt</option>
<option value="Brother" <?php if ($_POST['RelationToCF'] == "Brother") { echo "selected"; } ?>>Brother</option>
<option value="Caregiver" <?php if ($_POST['RelationToCF'] == "Caregiver") { echo "selected"; } ?>>Caregiver</option>
<option value="Child" <?php if ($_POST['RelationToCF'] == "Child") { echo "selected"; } ?>>Child</option>
<option value="Cousin" <?php if ($_POST['RelationToCF'] == "Cousin") { echo "selected"; } ?>>Cousin</option>
<option value="Friend" <?php if ($_POST['RelationToCF'] == "Friend") { echo "selected"; } ?>>Friend</option>
<option value="Grandma" <?php if ($_POST['RelationToCF'] == "Grandma") { echo "selected"; } ?>>Grandma</option>
<option value="Grandpa" <?php if ($_POST['RelationToCF'] == "Grandpa") { echo "selected"; } ?>>Grandpa</option>
<option value="Guardian" <?php if ($_POST['RelationToCF'] == "Guardian") { echo "selected"; } ?>>Guardian</option>
<option value="Husband" <?php if ($_POST['RelationToCF'] == "Husband") { echo "selected"; } ?>>Husband</option>
<option value="Nephew" <?php if ($_POST['RelationToCF'] == "Nephew") { echo "selected"; } ?>>Nephew</option>
<option value="Niece" <?php if ($_POST['RelationToCF'] == "Niece") { echo "selected"; } ?>>Niece</option>
<option value="Partner" <?php if ($_POST['RelationToCF'] == "Partner") { echo "selected"; } ?>>Partner</option>
<option value="Sister" <?php if ($_POST['RelationToCF'] == "Sister") { echo "selected"; } ?>>Sister</option>
<option value="Uncle" <?php if ($_POST['RelationToCF'] == "Uncle") { echo "selected"; } ?>>Uncle</option>
<option value="Wife" <?php if ($_POST['RelationToCF'] == "Wife") { echo "selected"; } ?>>Wife</option>
</select>
</div>
Here is the JavaScript chunk:
<script type="text/javascript">
function switch_distance(el) {
if(el.value == 'self') {
document.getElementById('self_cf_box').style.display = "block";
document.getElementById('RelationToCF_self').disabled = false;
document.getElementById('others_cf_box').style.display = "none";
document.getElementById('RelationToCF_others').disabled = true;
}else{
document.getElementById('self_cf_box').style.display = "none";
document.getElementById('RelationToCF_self').disabled = true;
document.getElementById('others_cf_box').style.display = "block";
document.getElementById('RelationToCF_others').disabled = false;
}
}
</script>
The best way to accomplish this is to use JavaScript for loading the values and validation. I would use a framework to make it easier.
ExtJS
Dojo
JQuery
are a few of the most well known. These have form validators built in along with AJAX functionality to make your like easier.
See http://www.extjs.com/deploy/dev/examples/form/dynamic.html
The best solution is to validate on the PHP side (using AJAX) and return the validation result as JSON. Also see here.

Categories

Resources