PHP drop down which each are dependable - php

I have this problems. using html and php.
May I know how to do this. I have 2 drop down, eg A and B. Drop down B is depend to the drop down A. Example, A have these options which will be called from dbase(no prob with this, tq) (Jack, Carol), and B wil have options depend on A: if select Jack(T1, T2, T3), if select carol(T1,T2,T3,T4,T5).
Here are the sample interface.
Can someone help me with this?
thank you.

U need to Work with Ajax In this Case. Without Refreshing the Page Selecting any of the A column will give u corresponding B column Value. For Example
<form method="post" name="form1">
<table border="0" cellpadding="0" cellspacing="0" width="60%"><tbody>
<tr>
<td width="150">Country</td>
<td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option> </select></td>
</tr>
<tr>
<td>State</td>
<td>
<p id="statediv">
<select style="background-color: #ffffa0" name="state"><option>Select Country First</option> </select></td>
</tr>
<tr>
<td>City</td>
<td>
<p id="citydiv">
<select style="background-color: #ffffa0" name="city"><option>Select State First</option> </select></td>
</tr>
</tbody></table>
</form>
As you can see above, in the onChage event of the country drop down getState() function of the javascript is called which change the options values the State drop down, let’s look at the code the getState() function.
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The code of the PHP file findState.php, which populate the options in the drop down of the state which is fetched from Ajax , is given below
<? $country=intval($_GET['country']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?=$country?>,this.value)">
<option>Select State</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['id']?>><?=$row['statename']?></option>
<? } ?>
</select>
In the above state dropdown, getCity() function is called in onChage event with countryId and stateId parameter, now let’s look at the code of the getCity() function
function getCity(countryId,stateId)
{
var strURL="findCity.php?country="+countryId+"&state="+stateId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
In the above ajax function, findcity.php is called and this PHP file populate the city dropdown according to the supplied parameters country and state from get method. Now let’s look at the code of findcity.php,
<?php $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);
?>
<select name="city">
<option>Select City</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['city']?></option>
<?php } ?>
</select>
And thats all, the triple drop down list of city, country and state using Ajax and PHP will be populated.

You will need Ajax bound to the onClick of Drop Down A that is set to populate the inner HTML of Drop Down B

Ajax is "cool" thing right now so everyone is going to say use ajax. I'm going to say you don't NEED ajax. An alternative would be to disable the second form. When the first select is submitted/changed the page reloads adding something to the querystring e.g. ?a=jack and the second select is populated with the correct values.
Now any pages linking to ?a=jack will automatically populate the second select, when with ajax youd have to write even more javascript code.
I'm not saying don't use ajax, im just giving a different, most likely easier alternative.
Only use ajax when it really helps the user experience.

ONE way to do it if you absolutely do not want to use jQuery nor javascript:
<form action="?step=2" method="post">
<select name="name">
<option if($_POST['name'] == 'Jack'){echo ' selected="selected" ';}>Jack</option>
<optionif($_POST['name'] == 'Carol'){echo ' selected="selected" ';}>Carol</option>
</select>
<?php if($_GET['step'] == 2){?>
<select name="b">
<option>1</option>
<option>2</option>
<option>3</option>
<?php if($_POST['name'] == 'Carol'){?>
<option>4</option>
<option>5</option>
<?php } ?>
</select>
</form>
<?php } ?>
<input type="submit" name="next" value="Next" />
You will have to breack the form/page into steps. And the whole form needs to be re-populated as the pages are reloaded.
Hope this can be of assistance to you

I think this tutorial explains what you're trying to achieve: Dependable Dropdown Menus with jQuery and PHP

Related

Button is not working when AJAX is using to display data based on drop down menu selection

I have a we page (index.html), where user can select option from drop down menu. Based on the selection data will be fetched from database and be displayed on the same page using AJAX (second file is called getParameter.php). Everything works fine. Now I tried to add a Button so that a new page will open and user can edit and send new value to database. But the button press does nothing. I tried it with other html files. It works everywhere else. Any help please
Index.html
//AJAX
<script>
function showParameterData(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getParameterData.php?q="+str,true);
xmlhttp.send();
}
}
</script>
//drop down option selection
<body>
//showParameterData() is the function
<form>
<select name="Device" onchange="showParameterData(this.value)">
<option value="">Select</option>
<option value="1">Device A </option>
<option value="2">Device B </option>
<option value="3">Device C </option>
<option value="4">Device D </option>
<option value="5">Device E </option>
<option value="6">Device F </option>
</select>
</form>
//bitton to edit and send data
<div class="edit_button_class" style= "float:right;">
<form action="edit.html" method="get" target="_blank">
<input type="submit" name="submit" id ="mybutton1" value="Click to Edit" />
</form>
</div>
<div id="txtHint"></div>
</body>
//getParameter.php
<?php
$q = intval($_GET['q']);
include ("DBconnect.php");
$conn= mysqli_connect( $dbhost, $dbuser, $dbpass, $db ) or die("Could not connect: " .mysqli_error($conn) );
$sql="SELECT * FROM parameter WHERE ID = '".$q."'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
$price = $row['price'];
$version = $row['version'];}
echo '<table>';
echo "<tr>
<th>Price of the Device :</th>
<td > $price </td>
</tr>";
echo "<tr>
<th>version of the Device :</th>
<td > $version </td>
</tr>";
echo '</table>';
echo '</div>';
When I press the button URL is changing to something weird. It is not going to edit.html. Even if I refresh the page, the weird URL is still there. Even though it shows index.html page some extra stuff in the URL
The stuff you are seeing in the URL are get parameters. You by using method='get' you are telling the form to submit in this way.
What this will do is send all the names of the inputs and their values into the URL and "attach" them to the action page you have chosen.
For example, you clicking the button will send you to edit.html with the get parameters of submit and the value of this which is "Click to Edit". Anything that has the name attribute will be sent as a get parameter. You dont need a name for a submit input.
If you place your select into the form with the submit button, it will send the parameter for the select and that means you can use it in your edit page.
<div class="edit_button_class">
<form action="edit.html" method="get" target="_blank">
<select name="Device" onchange="showParameterData(this.value)">
<option value="">Select</option>
<option value="1">Device A </option>
<option value="2">Device B </option>
<option value="3">Device C </option>
<option value="4">Device D </option>
<option value="5">Device E </option>
<option value="6">Device F </option>
</select>
<input type="submit" id ="mybutton1" value="Click to Edit" />
</form>
</div>
I removed the name from the input as this causes it to be sent as a GET parameter. Using the above you will be sent to /edit.html?submit=Click+to+Edit which you can then use in your edit page to get what you need.
Hope this helps.

Insert ajax populated dropdown into database in php

<select id="country" name="country" onChange="getState(this.value)" class="dropdown">
<option value="0">Select Country</option>
<?php
echo $country;
?>
</select>
the above code takes country from database, according to the country using ajax, i have created one dropdown using below code, am not able to insert the state value. how can I get the state value in php dbpage for inserting the state valu
<div id="statediv" >
<select id="ddlstate" name="ddlstate" class="dropdown" value="0">
<option>Select Country First</option>
</select>
</div>
this is my full ajax code
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
}
else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
this is findState.php
<?php $country=intval($_GET['country']);
$query="SELECT stateid,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['stateid']?>>
<?php echo $row['statename']?>
</option>
<?php } ?>
</select>
As long as your Ajax is generating and populating the drop down properly, like so:
<select id="country" name="country" onChange="getState(this.value)" class="dropdown">
<option value="0">Select Country</option>
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
</select>
Check with firebug, or by viewing the source code of the page. Once you know thats correct, submit the form and use PHP code like this to check:
if( isset($_REQUEST['country'] ) ) {
echo $_REQUEST['country'];
} else {
echo "Country not sent from form";
}
Once you know the country is being sent from your form, you can use the value to put into a database or whatever you like.
please find the states using countryid and execute in such a manner.
<?php $states= getStates($countryid);
$str ='';
$str .='<select id="ddlstate" name="ddlstate" class="dropdown" value="0">';
foreach($states as $val){
$str.='<option value="'.$val->id.'">'.$val->name.'</option>';
}
$str.='</select>';
echo $str; exit; ?>
This is just sample code which you need to use in php file
I guess your insert into query is wrong. Check the number of fields and the values provided.
insert into query_mas(employee_id,country_id,state_id,city_id,experience,query) values('".$employee_id."','".$country_id."','".$state_id."','".$city_id."','".$e‌​xperience."')";

unable to fetch value from second dynamic dependent drop down box

I hope my whole day trouble will at least be over by now. I have 2 drop down box. After submitting I have only first's dropdown box value in the action page. My second drop down box is dependent on the value selected in first dropdown box.
This is the ajax code in head section
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getScreen(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('screendiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
and this is the body of the page
<form method="post" action="a.php" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Device Name</td>
<td width="150"><select name="device" onChange="getScreen('finddevice.php?device='+this.value)">
<option value="">Select device</option>
<option value="1">Iphone 3</option>
<option value="2">Iphone 4</option>
<option value="3">Ipad </option>
<option value="4">android </option>
</select></td>
</tr>
<tr style="">
<td>Screen</td>
<td ><div id="screendiv"><select name="screen">
<option>Select Screen</option>
</select></div></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
It call the finddevice.php page which has following codes
<? $device=$_REQUEST['device'];
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('future');
$query="select screen from screen where device_id=$device";
$result=mysql_query($query);
?>
<select name="screen">
<option>Select Screen</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['screen']?></option>
<?php $row['device_id'] ?>
<? } ?>
</select>
Its working perfectly and bringing the value from the table into the second dropdown box upon selection of the value from the first dropdownbox. But when I submit the data, I can only access the first dropdown box value in the a.php file using $_POST method. That means I can only get the value of $_POST['device'] but there is not value from $_POST['screen']. Please help me out.
In finddevice.php, line 14 (as above) you seem to have missed value of option in 2nd drop down
I mean <option value> should be something like <option value="1">
Try filling in id or something unique as value for options in 2nd drop down
Unless you fill in values of options, 2nd drop down will submit blank value to a.php
finddevice.php:
<?php
$device=$_REQUEST['device'];
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('future');
$query="select id, screen from screen where device_id=$device";
//if screen table contains id field ...
//replace id with primary key or any unique identifier for screen table
//if there aint any primary key in "screen" table, use a field that is unique
//or create a primary key
$result=mysql_query($query);
?>
<select name="screen">
<option>Select Screen</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<!-- <option value><?=$row['screen']?></option> -->
<option value="<?php echo $row['id']; ?>"><?php echo $row['screen']; ?></option>
<?php } ?>
</select>

Dynamically generated dropdown in Wordpress options page

I've got a plugin I'm working on, part of which consists of a 'conditional' dropdown on the options page. Basically, I've got a dropdown with three options, and a second dropdown gets populated with info from the database depending on what is selected in the first dropdown. Problem is, I'm at a loss as to how to populate the second dropdown! I'm not really that great with AJAX, but it seems the likely solution. Any thoughts from the more seasoned devs out here?
EDIT: Here's where I currently am, but it never seems to get run:
<form action="<?php echo site_url() ?>/wp-admin/admin.php?page=ad_manager&pagetype=addedit&pid=<?php echo $_REQUEST['id']; ?>" method="post" name="ad_success">
<table cellpadding="5" class="widefat post fixed">
<thead>
<tr>
<th><strong><?php if($_REQUEST['id'] != '') { _e('Edit Ad'); } else { _e('Create Ad'); } ?></strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label for="gtad_condition">
<strong><?php _e('Ad Condition'); ?>:</strong>
<select name="ad_condition" id="ad_condition">
<option value="">Select an option...</option>
<option value="is_city">Is City</option>
<option value="is_location">Is Location</option>
<option value="is_page">Is Page</option>
</select>
</label>
<label for="gtad_location">
<select name="ad_location" id="ad_location"></select>
</label>
</td>
</tr>
</tbody>
</table>
</form>
<script>
jQuery(document).ready(function() {
$ad_condition = $("select[name='ad_condition']");
$ad_location = $("select[name='ad_location']");
$ad_condition.change(function() {
if ($(this).val() == "Is City") {
$("select[name='ad_location'] option").remove();
$("<option>Test</option>").appendTo($ad_location);
}
});
});
</script>
The reason why your code above does not work, is because $("mySelect").val() returns the value attribute of the <option>, not the text between the beginning and end tag. See my fiddle: http://jsfiddle.net/XhujD/ .
So, you solve the problem by changing
if ($(this).val() == "Is City") {
into
if ($(this).val() == "is_city") {
Using AJAX to populate the second dropdown when the first one has changed will basically look as follows:
// wait until the first list has changed
$("#list1").change(function(){
// call a script using AJAX and pass the selected value
$.post('myScript.php', {myValue: $(this).val()}, function(data){
// clear the second list
$("#list2").find("option").remove();
// add the options based on the 'data' variable
$("#list2").append('<option value="myOption">' + data + '</option>')
});
});

Basics of dynamic loading a drop down box

I'm new to php/ajax and to an extent sql. I'm trying to add a dynamic drop down box which when select will either load up another drop down box with dates or another text box. Can someone point me towards some simple examples that are not very confusing. I understand that ajax is best for this.
script
function showfield(name){
if(name=='byreturn')document.getElementById('div1').style.display="block";
else document.getElementById('div1').style.display="none";
}
if(name=='forwardorder')document.getElementById('div2').style.display="block";
else document.getElementById('div2').style.display="none";
}
function hidefield() {
document.getElementById('div1').style.display='none';
}
page
<tr><td> <body onload='hidefield()'>
Choose Delivery Type </td>
<td> <select name = 'elementtype1'id='elementtype1' onchange='showfield(this.options[this.selectedIndex].value)'>
<option value='forwardorder'>Forward Order</option>
<option value='byreturn'>By Return</option>
</select></td>
<td>
<div id='div1'>Enter By Return Date<input type='text''name='whatever1' />
</div>
<div id='div2'>
<td>Capacity</td>
<td><select name='deliveryDate'>
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
<option value='" . $x[cap] . "'</option>;
</div>
</td></tr>
This is very simple
<select name="first" onChange="populateNextBox(this)">
<options value="1">Microsoft</options>
<options value="2">Oracle</options>
</select>
<div id="populate"></div>
When user select the value from the drop down
required java script function
function populateNextBox(e) {
alert(e.value); //will print the selected value
//used jquery for populating data
$.post('ajax/test.php?id='+e.value, function(data) {
$('#populate').html(data);
});
}
//Your ajax/test.php will create the content for the dropdown

Categories