I have database with 5 tables. Each table is a subcatagory of the previous one, called:
countries
states
cities
ZIPcode
streets
Now I have 3 dropdowns which depend on each other. So when I select countries: USA, the next dropdown wil only show USA-states etc. This works.
But now I want to extend to 5 dropdowns, so adding 2 more.
I don't show what I've tried to add 2 more, because it will probably only make it more complex.
So I show the 3 dropdowns that are working now:
file: ajax.php
<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
****The index.php-file**** (I didn't add the css):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
</head>
<body>
<div class="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');
//Get all country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
</div>
</body>
</html>
You need to create a two more table zipcode and streets and add a city_id in zipcode table and zip_id in streets table
<select name="zipcode" id="zipcode">
<option value="">Select Zipcode first</option>
</select>
<select name="streets" id="streets">
<option value="">Select Streets first</option>
</select>
Jquery Scrtipt
$('#city').on('change',function(){
var cityId = $(this).val();
if(cityId){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'city_id='+cityId,
success:function(html){
$('#zipcode').html(html);
}
});
}else{
$('#zipcode').html('<option value="">Select zipcode first</option>');
}
});
});
$('#zipcode').on('change',function(){
var zipId = $(this).val();
if(zipId){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'zip_id='+zipId,
success:function(html){
$('#streets').html(html);
}
});
}else{
$('#streets').html('<option value="">Select Streets first</option>');
}
});
});
Php code is same as state just need to change table name and fields
By using this you get the cascading dropdown menu of zipcode and streets.
See, I modified your code a little bit.
I don't have any idea about your street & zipcode table column name or dropdown. I assumed and did.
Change it wherever needed in dropdow or in query.
It will help you.
Go through it.
And, if any doubt, feel free to ask.
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div class="select-boxes">
<?php include('dbConfig.php'); //Include database configuration file ?>
<div class="country">
<?php
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
if ($rowCount > 0) {
while ($row = $query->fetch_assoc()) {
echo '<option value="' . $row['country_id'] . '">' . $row['country_name'] . '</option>';
}
} else {
echo '<option value="">Country not available</option>';
}
?>
</select>
</div>
<div class="showStateCity">
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<select name="zipcode" id="zipcode">
<option value="">Select City first</option>
</select>
<select name="streets" id="streets">
<option value="">Select Zipcode first</option>
</select>
</div>
</div>
</body>
</html>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
getStateCityZipCodeStreets();
});
$('#state').on('change',function(){
getStateCityZipCodeStreets();
});
$('#city').on('change',function(){
getStateCityZipCodeStreets();
});
$('#zipcode').on('change',function(){
getStateCityZipCodeStreets();
});
function getStateCityZipCodeStreets(){
var country = $('#country').val();
var state = $('#state').val();
var city = $('#city').val();
var zipcode = $('#zipcode').val();
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{country_id:country, state_id :state, city_id : city, zipcode_id : zipcode},
cache:false,
success:function(data){
$('.showStateCity').html(data);
}
});
}
});
</script>
ajaxData.php
<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');
/*States*/
$queryState = "SELECT * FROM states WHERE 1=2";
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
$queryState = "SELECT * FROM states WHERE status = 1 AND country_id =".$_POST['country_id']." ORDER BY state_name ASC";
}
$execQueryState = $db->query($queryState);
$rowCountState = $execQueryState->num_rows;
/*City*/
$queryCity = "SELECT * FROM cities WHERE 1=2";
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
$queryCity = "SELECT * FROM cities WHERE status = 1 AND state_id".$_POST['state_id']." ORDER BY city_name ASC";
}
$execQueryCity = $db->query($queryCity);
$rowCountCity = $execQueryCity->num_rows;
/*ZipCode*/
$queryZipcode = "SELECT * FROM zipcode WHERE 1=2";
if(isset($_POST["city_id"]) && !empty($_POST["city_id"])){
$queryZipcode = "SELECT * FROM zipcode WHERE status = 1 AND city_id".$_POST['city_id']." ORDER BY zipcode ASC";
}
$execQueryZipCode = $db->query($queryZipcode);
$rowCountZipCode = $execQueryZipCode->num_rows;
/*Streets*/
$queryStreets = "SELECT * FROM streets WHERE 1=2";
if(isset($_POST["zipcode_id"]) && !empty($_POST["zipcode_id"])){
$queryStreets = "SELECT * FROM streets WHERE status = 1 AND zipcode_id".$_POST['zipcode_id']." ORDER BY street_name ASC";
}
$execQueryStreets = $db->query($queryStreets);
$rowCountStreets = $execQueryStreets->num_rows;
?>
<select name="state" id="state">
<option value="">Select country first</option>
<?php
if($rowCountState > 0){
while($rowState = $execQueryState->fetch_assoc()){
?>
<option value="<?php echo $rowState['state_id'];?>"><?php echo $rowState['state_name'];?></option>
<?php }
} else {?>
<option value="">State Not Available</option>
<?php }?>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
<?php
if($rowCountCity > 0){
while($rowCity = $execQueryCity->fetch_assoc()){
?>
<option value="<?php echo $rowCity['city_id'];?>"><?php echo $rowCity['city_name'];?></option>
<?php }
} else {?>
<option value="">City Not Available</option>
<?php }?>
</select>
<select name="zipcode" id="zipcode">
<option value="">Select City first</option>
<?php
if($rowCountZipCode > 0){
while($rowZipCode = $execQueryZipCode->fetch_assoc()){
?>
<option value="<?php echo $rowZipCode['zipcode_id'];?>"><?php echo $rowZipCode['zipcode'];?></option>
<?php }
} else {?>
<option value="">ZipCode Not Available</option>
<?php }?>
</select>
<select name="streets" id="streets">
<option value="">Select ZipCode first</option>
<?php
if($rowCountStreets > 0){
while($rowStreets = $execQueryStreets->fetch_assoc()){
?>
<option value="<?php echo $rowStreets['street_id'];?>"><?php echo $rowStreets['street_name'];?></option>
<?php }
} else {?>
<option value="">Streets Not Available</option>
<?php }?>
</select>
Related
I had created a simple on change event in Ajax and trying to get data on the change of select tag [HTML] in another select tag.
All's work fine I got the result on test.php
test.php
<div class="row">
<div class="input-field col s12">
<select name="category" id="category">
<option value="" disabled selected>Choose Category</option>
<?php
include "db-connect/db-connect.php";
$qry = mysqli_query($conn, "SELECT * FROM `category`");
while ($row=mysqli_fetch_assoc($qry)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select name="subcategory" id="subcategory">
<option value="">Choose Sub Category</option>
</select>
</div>
</div>
and the ajax code for this html :-
<script type="text/javascript">
$(document).ready(function(){
$('#category').on('change',function(){
var categoryID = $(this).val();
if(categoryID){
$.ajax({
type:'POST',
url:'ajax/category.php',
data:'category_id='+categoryID,
success:function(html){
$('#subcategory').html(html);
//$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#subcategory').html('<option value="">Choose category first</option>');
//$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
When I run it I got the result but after that, I want to implement it into my project template I got nothing.
But, I get data in the inspect element [F12] -> Network
Ajax data file ajax/category.php:-
<?php
//Include the database configuration file xD
include "../db-connect/db-connect.php";
if(!empty($_POST["category_id"])){
//Fetch all data
$query = mysqli_query($conn,"SELECT * FROM `sub_category` WHERE `category_id` = ".$_POST['category_id']."");
//option list
if(mysqli_num_rows($query) > 0){
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_assoc($query)){
echo '<option value="'.$row['sub_category'].'">'.$row['sub_category'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
?>
I have two dropdown. I am using Jquery to load second dropdown. without jqyery My php code is working fine. but when I use with jquery second dropdown becomes empty on selection of first drop down.
First Dropdown ( Education )
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
Second Drop Down ( Degree)
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
</select>
Second dropdown is using juery to load on selection of first dropdown Education.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#education').on('change',function(){
var educationID = $(this).val();
if(educationID){
$.ajax({
type:'POST',
url:'education-career.php',
data:'education_id='+educationID,
success:function(html){
$('#degree').html(html);
}
});
}else{
$('#degree').html('<option value="">Select Education first</option>');
}
});});</script>
Try change below line
data:'education_id='+educationID,
to
data:{education_id : educationID},
Try this.(second select tag have to place in first page in order to use $('#degree').html(...))
First Dropdown
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
</select>
Second Dropdown
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
Here in ajax, you are using the
data:'education_id='+educationID,
Which is used to post the data. and the variable name will be here education_id.
And in your second page you are trying to get:
isset($_POST["education"])
this only. So on second page you have to replace education with education_id.
change:
$('#education').on('change',function(){
To:
$('select#education').change(function(){
I have three dropdown list which is country,state and city. At first, the country dropdown would be displayed with all countries. When a country would be chosen, the respective states would be fetched from the MySQL database and appear in the states dropdown. Alike when a state would be chosen, the respective cities will be fetched from the MySQL database and appear in the cities dropdown.
Below is the default display before I select country,state,city and click submit button.
After I select country, state, city and click submit button like below. It will refresh and go back to the default display.
So how can I keep the selected value(United Kingdom,England,London) display in the dropdown list instead it jump back to default display after clicked submit button?
Index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
.select-boxes{width: 280px;text-align: center;}
</style>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
</head>
<body>
<form id="form1" name="form1" method="get" action="<?php echo $_SERVER['PHP_SELF'];?>">
<?php
//Include database configuration file
include('dbConfig.php');
//Get all country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
ajaxData.php
<?php
//Include database configuration file
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM states WHERE country_id IN (".$_POST['country_id'].")");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM cities WHERE state_id IN(".$_POST["state_id"].")");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
dbConfig.php
<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'location_db';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Firstly do this:
<select name="country" id="country">
<option value="">Select Country</option>
<?php
$selectedCountry = filter_input(INPUT_POST, "country");
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'" '.($selectedCountry==$row['country_id']?"selected='selected'":"").'>'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
Then on your document ready event do:
<script type="text/javascript">
$(document).ready(function(){
$("#country").one("finishedLoading", function () {
setTimeout(function () {$("#state").val("<?= (filter_input(INPUT_POST,"state")?:"[]") ?>").trigger("change")},10);
});
$("#state").one("finishedLoadingState", function () {
setTimeout(function () { $("#city").val("<?= (filter_input(INPUT_POST,"city")?:"[]") ?>").trigger("change") }, 10);
});
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
$("#country").trigger("finishedLoading"); //Little custom event we can listen for
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
$("#country").trigget("finishedLoading");
}
}).trigger("change"); //Trigger immediately in case there's a value pre-selected
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
$("#state").trigger("finishedLoadingState");
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
$("#state").trigger("finishedLoadingState");
}
});
The idea is you chain trigger the "change" events the same way a user might.
you can do it using hidden filed
<input type="hidden" name="selectedoption" value="<?php echo !empty($_POST['selectedoption']) ? strip_tags($_POST['selectedoption']) : ''; ?>" />
<select id="sortSelect" class="selctedcls" size="1" name="selectedoption" onchange="this.form.submit();" >
<option selected>value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
</select>
<script type="text/javascript">
document.getElementById('selctedcls').value ="<?php if(! $_POST['selectedoption']):?>"selectedoption"<?php else: echo $_POST['selectedoption']; endif;?>";
</script>
I beginner on javascript
I have select component that contains list of class and input that contains datalist name from table in mysql
here my simple code :
<select class="form-control" name="class" id="class" onchange="" value="--">
<option>--</option>
<option>X NET 1</option>
<option>X NET 2</option>
<option>XI NET 1</option>
<option>XI NET 2</option>
</select>
<input type="text" class="form-control" name="name" id="name" list="checkName" autocomplete="off" required>
<datalist id="checkName">
<?php
$sql_siswa = "SELECT name,class from student order by name;";
$result = $conn->query($sql_siswa);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo "<option value=\"".$row["name"]."\">";
}
}
?>
</datalist>
so, I want if I select class, datalist will retrieve name student by class from filter by php.
here filtering like this:
$sql_siswa = "SELECT name from student where class like '".$_POST["class"]."' order by name;";
$result = $conn->query($sql_siswa);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<option value=\"".$row["name"]."\">";
}
}
how to implement this filter in onchange?
I'm sorry, I have not try anything because I have no idea what should I do.
You should try ajax to do that
<select class="form-control" name="class" id="class" onchange="ajax_change(this.value)" >
<option value="">--</option>
<option value="X NET 1">X NET 1</option>
<option value="X NET 2">X NET 2</option>
<option value="XI NET 1">XI NET 1</option>
<option value="XI NET 2">XI NET 2</option>
</select>
In your script
function ajax_change(str){
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {class: str},
success: function (data) {
$("#checkName").html(data);
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
}
In your ajax.php
//include connection
if(isset($_POST["class"])){
$sql_siswa = "SELECT name from student where class like '".$_POST["class"]."' order by name;";
$result = $conn->query($sql_siswa);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<option value=\"".$row["name"]."\">";
}
}
}
I'm trying to post the values that I get from each dropdown menu, this is an n-level, however I'm going to use them maximum of 3. How can I post every value i get from each selection?
<?php
include('dbcon.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query = "select * from ajax_categories where pid = ".$id;
$results = #mysql_query( $query);
$num_rows = #mysql_num_rows($results);
if($num_rows > 0)
{?>
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['id'];?>"><?php echo $rows['category'];?></option>
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
?>
http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
change the select option of your like this
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
while ($rows = mysql_fetch_assoc(#$results))
{?>
echo '<option value="'.$row['id'].'">'.$rows['category'].'</option>';
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
</select>