get selected item from a dropdown list and save it to a php variable - php

I have a dropdown list(in a php file and without form tag)
print "<select id="animal" onchange="getSelectedItem(this.value)">
<option value = "Dog"> Dog </option>
<option value = "Cat"> Cat </option>
</select>";
and a variable $selAnimal
and a javascript function
function getSelectedItem(opt){
//$selAnimal = opt <- how do i do this?
}
As much as possible I wouldn't like the page to reload so I avoid putting this inside a form and submitting as I select. I can't get to make $.post method work. I know for a fact that this cannot be directly done since php is server side and javascript is client side.
I also thought of putting the selected value inside a hidden component(span or something) and get the value from it. But I have no idea how to get it from the component. I've also seen use of AJAX or jquery but I'm not really knowledgeable enough.
I need to save this value to the php variable since I'll be using it as basis for the options in my second dropdown. For example, if I choose Dog, the dropdown list would have dog breeds as options.
I've spent days looking for possible solutions everywhere. Help would be very much appreciated. Thank you!

here is the solution
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#animal').change(function(){
$.post('loadbreeds.php', { animal:$('#animal').val() },
function(data){
$('#breedList').html(data);
});
});
});
</script>
<form method="post" >
<div id="animalList">
<select id="animal" name="animal">
<option value="">--Select--</option>
<?php if (!empty($animals)) { foreach ($animals as $value) { ?>
<option value="<?php echo $value['animalKey']; ?>"><?php echo $value['animalName']; ?></option>
<?php }} ?>
</select>
</div>
<div id="breedList">
<select id="breed" name="breed">
<option value="">--Select--</option>
</select>
</div>
<input type="submit" value="Submit" />
</form>
code for loadbreeds.php
$animalKey = $_POST['animal'];
$breeds = selectByKey($animalKey); // code for selecting breeds
<select id="breed" name="breed">
<option value="">--Select--</option>
<?php if (!empty($breeds)) { foreach ($breeds as $value) { ?>
<option value="<?php echo $value['breedKey']; ?>"><?php echo $value['breedName']; ?></option>
<?php }} ?>
</select>

You cannot have the variable available to the same file since PHP declares all its variables before the JS even starts. You can however simply redirect the user to a new file where the variable is available.
Use something like this:
function getSelectedItem(opt){
location.href = location.href + "?selAnimal=" + opt;
}
In PHP, now you can use the selAnimal variable to display something different, like this:
$selectedAnimal = $_GET["selAnimal"];
if($selectedAnimal == "dog"){
// Whatever you want to do now
}
A better way would be to use POST with forms, but this should work fine for you as well.

Try the following, to rebuild the second dropdown:
http://jsfiddle.net/kAY7M/59/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
print "<script type=\"text/javascript\">var AnimalTypeList = [\"Dog1,Dog2,Dog3,Dog4\",\"Cat1,Cat2,Cat3,Cat4\"];</script>";
<script type="text/javascript">
$("#animal").change(function () {
var sel = $("#animal").prop("selectedIndex") - 1;
var list = AnimalTypeList[sel].split(",");
var Counter = list.length;
$("#type").children().remove();
for (var i = 0; i < Counter; i++) {
$("#type").append("<option value = '" + list[i] + "'> " + list[i] + "</option>");
}
})
</script>
I could do a pure Javascript only version too, but that is a bit more code.

Related

PHP concatenation $i in jQuery

Bit of a strange one, I have a webpage that iterates through a set number of times using while ($i <= 21):. During this iteration I have a dropdown in each which displays some values I pulled from a database, at this point that specific value doesn't matter but the id of each dropdown uses the value of $i. For example:
<select name="dropdown<?php echo $i; ?>" id="dropdown<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
What I am then wanting to do is take the value selected from that dropdown and place in another field that also has the id corresponding to the iteration number, for example:
<textarea name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>"></textarea>
I am using the following code for the jQuery to get the value from the dropdown and put it into the textarea:
<script>
$("#dropdown<?php echo $i ?>").on("change",function(){
//Getting Value
var selValue = $("#dropdown<?php echo $i ?>").val();
//Setting Value
$("#textfield<?php echo $i ?>").val(selValue);
});
</script>
However it doesnt seem to like the use of <?php echo $i ?> part as if i replace that with for example 2 or 3 then it works for that iteration.
I have tried setting the variable in PHP like: $textfield= 'textfield'.$i; and the using this as a whole in jQuery like this: $("#<?php echo $textfield ?>").val(selValue); but it doesnt like that either. Interstining if I change it to $textfield= 'textfield'.'2'; or $textfield= 'textfield2'; it works. Seems like it doesnt like my use of $i, is it the PHP concatenation that it doesnt like?
Anyone experienced this or know of a fix?
Huge fixes are required in your code but will explain the solution in minimal coding.
use array in name,dont use id,use class and data attribute to store the loop value as follows
<select name="dropdown[]" class="dropdown" data-id="<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<textarea name="textfield[]" class="textfield<?php echo $i; ?>"></textarea>
now in script single piece of code is enough to perform your operation with the help of class dropdown and dynamic class textfield
<script>
$(".dropdown").on("change",function(){
//Getting Value
var selValue = $(this).val();
var dynamic_id = $(this).data('id');
//Setting Value
$(".textfield"+dynamic_id).val(selValue);
});
</script>

How to change a PHP variable depending on a <select> HTML

I'm currently making an auto-signature in PHP & HTML.
The variable 'layout' is the variable I want to change. It contains the structure of the Html signature (Background, logo, Structure).
$layout = file_get_contents('./SIG/SAELEN.html', FILE_USE_INCLUDE_PATH);
$layout1 = file_get_contents('./SIG/GUIL.html', FILE_USE_INCLUDE_PATH);
The Structure is supposed to change, depending on this :
<select class="form-control" id="sel1" id="Name" name="Sender[department]">
<option value="1">Choix1</option>
<option value="2">Choix2</option>
<option value="3">Choix3</option>
<option value="4">Choix4</option>
<option value="5">Choix5</option>
<option value="6">Choix6</option>
</select>
I wish to change the $layout value depending, on the user Selection without having to refresh the Page.
Thanks for taking the time to read, I'm looking forward to hearing your suggestions.
There is no possibility to change php variable without refreshing the page. But as per your requirement you can use techniques to achieve your goal. I suggest below solution for this using ajax call.
index.php
<?php?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#sel1').change(function(){
var getValue = $(this).val();
// alert(getValue);
//Ajax call
$.post('do.php', { selectedValue: getValue }, function(data){
//alert('check response value: '+data);
});
});
});
</script>
</head>
<body>
<select class="form-control" id="sel1" id="Name" name="Sender[department]">
<option value="1">Choix1</option>
<option value="2">Choix2</option>
<option value="3">Choix3</option>
<option value="4">Choix4</option>
<option value="5">Choix5</option>
<option value="6">Choix6</option>
</select>
</body>
</html>
do.php
<?php
// get posted value
if ($_POST['selectedValue']){
//echo "posted--". $_POST['selectedValue'];
// do your logic here
//$layout = file_get_contents('./SIG/SAELEN.html', FILE_USE_INCLUDE_PATH);
//$layout1 = file_get_contents('./SIG/GUIL.html', FILE_USE_INCLUDE_PATH);
}
?>
I hope you can get an idea by using this way.
we cannot change PHP variable from javascript. Php is backend and js
is frontend.
Solution is to call a ajax call when ever user changes the select input
or
you can store both layouts in two js variables and use them when user changes the select input
$layout = file_get_contents('./SIG/1.html', FILE_USE_INCLUDE_PATH);
$layout1 = file_get_contents('./SIG/2.html', FILE_USE_INCLUDE_PATH);
$layout2 = file_get_contents('./SIG/3.html', FILE_USE_INCLUDE_PATH);
$layout3 = file_get_contents('./SIG/4.html', FILE_USE_INCLUDE_PATH);
if(isset($_POST['select']))
{
if($_POST['select'] == 'value2')
{
$layout = $layout1;
}
if($_POST['select'] == 'value3') {
$layout = $layout2;
}
if($_POST['select'] == 'value4') {
$layout = $layout3;
}
}

Hold country value when submit

<label>Country <font color="8AC007">*</font> </label></td>
<td><select name="country" onchange="print_state('state',this.selectedIndex);" id="country"<?php
$sel_country = $myform->value('country');
if (isset($sel_country)) echo 'selected="selected"'; ?> />
<option value="<?php $myform->value("country"); ?>"/>Select country</option>
</select><br><?php $sel_country.'sample' ?>
<span class="error"><?php echo $myform->error("country"); ?></span>
I want to get hold with the country selected value when I submit form, instead filling the form from starting again. Here is the code Iam trying to get countries from a js file.
Apperciate your help
HTTP is stateless, so you have to put a little effort on keeping data around when moving from page to page. Seeing this as being a form with inputs (select in this case), you can use $_POST to get hold of your submitted value in the next page.
In this case you'd use $_POST['country']. If you want to keep the current form filled next time the page refreshes, make the form submit to the current page, then you'll have access to that value in $_POST.
Other ways to keep data around:
Sessions
Cookies
Database storage
But this require a little bit of additional coding in PHP.
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country"/>
<option <?php if($youroldval==$myform->value('country')){ echo 'selected="selected"'; } ?> value="<?php echo $myform->value("country"); ?>"/><?php echo $myform->value("country"); ?></option>
</select>
You must store your old value of form
Ok, if I am right you should do it as follows.
If you are posting your page to the server. You have the selected value. You store this and return this page. In that case I added bollow code and added $isSelected to the code. Normally it emtpy, but if the value is equal to the selected then you set selected='selected'.
<select name="country">
<?php
$countryList = array("USA", "UK", "France", "Germany", "India", "Netherlands");
$isSelected = "";
foreach($countryList as $country)
{
if($_POST["country"] == $country)
{
$isSelected = "selected='selected'";
}
echo "<option value='" + $country + "' " + $isSelected + ">" + $country + "</option>";
?>
</select>
If you are using jquery / Ajax, you have the selected value which stays selected because the page wont refresh :-) However, you can get the value by using javascript and get value from selectbox.
------ Edit
Mmm ok, I was in the illusion you had your array in php. However you get your collection from javascript. In that case you will get this as solution:
<script type="text/javascript">
var selectedCountry = "<?php echo $myform->value("country"); ?>";
</script>
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country">
/* This is generated by javascript */
</select>
Your javascript function will be like this:
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selectedCountry == country_arr[i])
{
option_str.options[option_str.length].setAttribute("selected", "selected");
}
}
}
----- Edit 2:
http://jsfiddle.net/eLProva/5mU76/ with filling and selecting the country

JavaScript count in line with PHP loop

I have a page with two drop-down menus. The option selected in the first drop-down menu controls what is displayed in the second.
The code was nice and easy when the drop-down menus were only used once - but I'm looking to repeat each set of drop-down menus four times.
Drop-down menu one is assigned the ID experience[<?php echo $i; ?>][manufacturer]. Drop-down menu two is assigned the ID experience[<?php echo $i; ?>][type].
Essentially, what I've got is:
<select id="experience[1][manufacturer]">...</select>
<select id="experience[2][manufacturer]">...</select>
<select id="experience[3][manufacturer]">...</select>
<select id="experience[4][manufacturer]">...</select>
... followed by:
<select id="experience[1][type]">...</select>
<select id="experience[2][type]">...</select>
<select id="experience[3][type]">...</select>
<select id="experience[4][type]">...</select>
I'm wondering: what's the best way to get the equivalent of <?php echo $i; ?> into the chunk of JavaScript that's used to output the contents of the second drop-down menu? (I know I can't use PHP directly within JavaScript like this - I just left the <?php echo $i; ?> snippets to indicate where I need to output numbers 1, 2, 3, 4 etc.
Thanks for your help!
Code:
<form>
<?php
$i=1;
while($i<=4) {
?>
<select id="experience[<?php echo $i; ?>][manufacturer]">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
<script type='text/javascript'>
$(document).ready(function() {
$("#experience[<?php echo $i; ?>][manufacturer]").change(function() {
$("#experience[<?php echo $i; ?>][type]").load("get_type.php?choice=" + $("#experience[<?php echo $i; ?>][manufacturer]").val());
});
});
</script>
</select>
<?php
$i++;
}
?>
</form>
Revised code:
<form>
<script type='text/javascript'>
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience["+$(this).attr('data-id')+"][type]").load("get_type.php?choice=" + $(this).val());
});
});
</script>
<?php $i=1;
while($i<=4) { ?>
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
</select>
<?php
$i++;
}
?>
</form>
You should not need to include the script element in your PHP loop.
Instead, you should add a similar class to all common select elements. Something like class="experience"
Then, with a single script element you can attach events to all the selects:
<script type='text/javascript'>
$(document).ready(function() {
$("select.experience").each(function(i,element){
// here element is the actual item from the selected set, i is its index
$(element).on("change", function() {
$("#experience[" + i + "][type]").load("get_type.php?choice=" + $(element).val());
});
});
});
</script>
Instead of repeating the same javascript code 4 times, put it outside your loop and give classes to your select elements and use them as selectors for your jquery code. You could then add an attribute (named data-id for example) to your select elements containg their ids. It would look something like this
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]"></select>
And your javascript code (outside the loop) would look something like this
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience\\["+$(this).attr('data-id')+"\\]\\[type\\]").load("get_type.php?choice=" + $(this).val());
});
});
Note that I used the keyword "this" inside the change event which references to the select element.
Edit: Added backslashes to escape the brackets in the jQuery selector (or else jQuery interprets it as an attribute).

How to use drop down menu to change PHP object variable?

The title may not be the best way to word this question, so please let me know if I can improve it.
What I am trying to do is use a drop down menu to change the value of a PHP object.
In the example below, I want $selected to be assigned as the "value" of the the menu option selected.
$selected = $_GET['program_select'];
Here is the drop down menu:
<select id="programs_select" name="programs_select">
<option>Select a Different Month</option>
<?
foreach($pagedata->programs as $programs){
?>
<option value="<?=$programs->id?>"><?=$programs->title?></option>
<?
}
?>
</select>
How can I send this value to the server and reload the page using the selected value?
For example, if the 2nd option is selected and it's id is 2 the result would be:
$selected = 2;
FYI, this is being used to dynamically generate the output data for a thumbnail menu. The "program" being displayed would be determined by the value in the option selected.
<select id="programs_select" name="programs_select" onchange="ihavechanges(this.options[this.selectedIndex].value)">
<option>Select a Different Month</option>
<?
foreach($pagedata->programs as $programs){
?>
<option value="<?=$programs->id?>"><?=$programs->title?></option>
<?
}
?>
</select>
<script type="text/javascript">
function ihavechanged(towhat)
{
document.location.href = "reload.php?id="+towhat;
}
</script>
<select id="programs_select" name="programs_select">
<option>Select a Different Month</option>
<?
$selected = $_GET['program_select'];
foreach($pagedata->programs as $programs){
$seld = ($selected == $program-id) ? 'selected' : '';
echo '<option value="'.$programs->id.'" '.$seld.'>'.$programs->title.'</option>';
}
?>
</select>
You are using GET in the php side. So, if you just want to know how to pass the value to your php file, then put your select tag into a form and add a submit button.
<form id="your_id" name="your_id" method="get" action="your_controller/your_function_name">
<select id="programs_select" name="programs_select">
<option>Select a Different Month</option>
<?
foreach($pagedata->programs as $programs){
?>
<option value="<?=$programs->id?>"><?=$programs->title?></option>
<?
}
?>
</select>
<input type="submit" id="submit" name="submit" value="GO">
</form>
In your controller, echo something based on the value.
$selected = $_GET['program_select'];
However, if your want to change the contents in the same page without refresh. You may need ajax call to do that, and I recommend the jQuery ajax api (http://api.jquery.com/jQuery.ajax/).
$("select#programs_select").live('change', function(){
var id = $("select#programs_select").val();
$.ajax({
type: "GET",
url: "your_controller/the_funstion_name?programs_select=" + id,
data: "",
contentType: "application/json; charset=utf-8",
success: function(msg) {
$("#your_thumbnail_menu_id").html(msg);
},
error: function() {
alert("Error! Ajax failed");
}
});
});
In your controller side, echo the html you need at last.
e.g:
$selected = $_GET['program_select'];
$html = "<ul><li>your menu $selected</li>";
$html .="<li>which depends on the id you got!</li></ul>";
echo $html;

Categories