Dependent dropdown list using PHP - php

I am trying to create a dropdown list to select State which is dependent on the another dropdown list Country.
Based on the Country selected from the first list, the second dropdown list should display corresponding states of the country.
For both the dropdown list I need to fetch values from the SQL server database.
Here is the code am trying:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#country").change(function(){
var country=$("#country").val();
$.ajax({
type:"post",
url:"getcity.php",
data:"country="+country,
success:function(data){
$("#city").html(data);
}
});
});
});
</script>
</head>
<body>
Country :
<select name="country" id="country">
<option>-select your country-</option>
<?php
include "dbconfig.php";
$sql = "SELECT [CountryId],[Country] from Country order by [Country]";
$result=sqlsrv_query($conn,$sql);
while($country = sqlsrv_fetch_array($result)){
echo "<option value = $country[CountryId]>$country[Country]</option>";
} ?>
</select>
City :
<select name="city" id="city">
<option>-select your city-</option>
</select>
</body>
</html>
Below is the getcity.php code :
<?php
include "dbconfig.php";
$country=$_POST["country"];
$sql= "select [StateID],[State] from State where CountryId='$country'";
$result=sqlsrv_query($conn,$sql);
while($city=sqlsrv_fetch_array($result)) {
echo"<option value='$city[StateID]'>$city[State]</option>";
}
?>
I made database connection code in the file dbconnection.php and it is working fine, successfully connected with the database.
When I run this code I am not able to get the dropdown list of states after selecting the country. The code doesn't return any error but dropdown list of state not appear after selecting the country.

Related

Get text from dynamic dropdown and use it in another file

On my web page I have two dropdown menus. One for a list of countries and another for a list of city's. The country menu is populated with data from a database. Once one of these countries are selected, the following dropdown is populated with corresponding cities via a php file (getdata.php) which takes the country value selected and queries it with a database and echos the city names into the dropdown. What I am struggling to work out is, when a city is selected, how would I get the text of the city selection and use this text in another php (displayCity.php) to query the database and echo values such as Population into the textbox (without reloading page) back on the web page? Would I need to make the displayCity.php similar to the getData.php? I have already created a new Ajax method for the textbox but I am not sure if I will need this. Advice would be greatly appreciated.
<?php include_once "connection.php"; ?>
<!DOCTYPE html>
<html>
<head>
<title>City displayer</title>
<h1>City displayer</h1>
<link rel="stylesheet" type="text/css" href="homepagestyle.css">
</head>
<body>
<div class = "country">
<label>Select Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) from location AS Country FROM location ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo $country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList" onchange="showCity(this.value)">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
</br>
<div id = "textbox">Choose a country and city to display city name here</div>
<script>
function showCity(value){
$.ajax({
type: "POST",
url: "displayCity.php",
data: "City="+value,
success: function(data){
$("#textbox").html(data);
}
});
}
</script>
</body>
</html>
getdata.php
<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$query = "SELECT * FROM location WHERE Country= '$country'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo
$city['City'] ?></option>
<?php
}
}
?>
Use AJAX along with a $_SESSION variable. No need to write it to the database. You just have to make sure you use session_start() everywhere you need it.

Building a dropdown based on another dropdown in php

New in php and ajax, building a dropdown based on another dropdown through database.Up to now code is sucessfully running, you can check my code having two php pages, dropdown2.php and postbrand.php now just want to know how to use $brand variable value in postbrand.php to use in the sql query in second dropdown in dropdown2.php.
<?php
require 'connect.inc.php';
$query = "SELECT * FROM `brand` ";
$data = mysql_query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Input form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12/jquery.min.js"></script>
</head>
<body>
<form>
<label>Brand:</label>
<select name="brand" id="sb" onchange="myFunction()">
<?php
while($row=mysql_fetch_array($data))
{
?>
<option value="<?php echo $row['b_name'];?>">
<?php
echo $row['b_name'];
?>
</option>
<?php
}
?>
</select>
<br/><br/>
<label>Model:</label>
<?php
$query = "SELECT model.model, model.b_id from model inner join brand on model.b_id= brand.b_id where brand.b_name like 'sony'";
$result = mysql_query($query);
$select= '<select name="select" id="sm">';
while($rs=mysql_fetch_array($result)){ $select.='<option value="'.$rs['b_id'].'">'.$rs['model'].'</option>';
}
$select.='</select>';
echo $select;
?>
</form>
<div id="result"></div>
<script>
function myFunction() {
//alert('working!!');
var brand = $('#sb').val();
$.post('postbrand.php', {postbrand:brand},
function(data){
$('#result').html(data);
});
}
</script>
</body>
</html>
postbrand.php
<?php
$brand = $_POST['postbrand'];
echo $brand;
?>
If I get it correct you want to populate the second dropdown based on the chosen value of the first dropdown.
To steps to achieve this are:
listen to "change" event on the first dropdown (using JQ)
var selected = ""
$('select#sb').on('change', function() {
selected = $(this).val(); // get the chosen value
});
$.post("postbrand.php", selected, function(resp){ //send the selected value to postbrand.php which will return an array of elements from db based on what was selected
$.each(resp,function(key, val){ //traverse the response and
$('select#secondDropdown').append('<option>'+val+'</option>') //populate the 2nd dropdown
})
})

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

dynamically updating select boxes with php mysql ajax

I am trying to populate an initial select box with results from mysql via php. Then I would like the second select box to update with additional information related to what was chosen in the first box.
Here I am selecting some campaign names, then in the second box i would like to update with the versions of the campaign stored in mysql.
here is the name script:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#campaign").change(function(){
var campaign = $("#campaign").val();
$.ajax({
type:"post",
url:"getversion.php",
data:"campaign="+campaign,
success: function(data) {
$("#version").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="campaign" id="campaign">
<option>-Select a Campaign-</option>
<?php
include "db_conn.php";
$result = mysql_query("SELECT campaign, time FROM dfa_data GROUP BY campaign");
while($row = mysql_fetch_array($result)){
echo "<option value=$row[campaign]>$row[campaign]</option>";
} ?>
</select>
Version :
<select name="version" id="version">
<option>-Select a Version-</option>
</select>
</body>
</html>
then there is another script that pulls in the second select box data, although it does not populate and I do not have any idea why.
<?php
include "db_conn.php";
$campaign = $_POST["campaign"];
$result = mysql_query("SELECT * FROM dfa_data where campaign='$campaign' GROUP BY time");
while($rowa = mysql_fetch_array($result)){
echo"<option value=$rows[time]>$rows[time]</option>";
}
?>
Can anyone show me what I am doing wrong and why the second select box will not populate. Thanks in advance.
Not sure if this is your issue, but it's probably AN issue. In your second script you have:
while($rowa = mysql_fetch_array($result)){
echo"<option value=$rows[time]>$rows[time]</option>";
}
You are fetching into $rowa, but trying to access $rows. Try this instead.
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['time'].'">'.$row['time'].'</option>';
}
I think rowa and rows are the errors. Try row instead of both

dynamically add options to a dropdown list that gets values from mysql database

I would like to add an option to a dropdown list without refreshing the form so that the other controls retain their values. I've tried looking for a tutorial but all I found are tutorials that dynamically populate a dropdown list with static options.
You have to get the option with an AJAX call and then use DOM to add an option to your dropdown in the request callback.
To facilitate this task, I recommend using the jQuery library:
http://jquery.com/
Lookup the ajax function:
http://api.jquery.com/jQuery.ajax/
So you would have 2 pages,
index.php:
<html>
<head>
</head>
<body>
<select id="dropdown">
<option value="default" selected="selected">Default option</option>
</select>
<script type="text/javascript">
$.ajax({
url: 'dropdown-choices.php',
success: function(data) {
$('#dropdown').append(data);
}
});
</script>
</body>
</html>
dropdown-choices.php:
<?php
$sql = mysql_query("SELECT * FROM dropdown_choices;");
while ($data = mysql_fetch_assoc($sql)) {
echo '<option value="'+$data['value']+'">'+$data['name']+'</option>';
}
?>
This should do it :)

Categories