Using ajax to make dropdown when state and city is selected
- First create page where you have embed or add state and city option(example: state_city.php)
- Then create an differente page from where we will receive response when state option is selected
There is three stages create select options for state and city then take data from server(state data) and display as select option as state, when state option is selected then the value inside state dropdown will go to ajax function to send request to other page, where city date is getting then display this page data as html in state page below;
see the source code you will understand completly.
This is ajax block whice receive data from state option
This page is included in main page where we have to display data
<script type="text/javascript">
$(document).ready(function() {
$('#state_dropdown').on('change', function() {
var state_id = this.value;
$.ajax({
url: "state_city.php",
type: "POST",
data: {
state_id: state_id
},
cache: false,
success: function(result){
$("#city_dropdown").html(result);
}
});
});
});
</script>
This is select option where we have to display state and then from state to city dropdown
<div class="row">
<div class="col-md-4">
<label for="label-floating"> Working Location</label>
</div>
<div class="col-md-3">
<div class="form-group">
<select class="custom-select" id="state_dropdown" >
<option>Select state</option>
<?php
$sql='select * from `state_name`';
$select=execute_query($sql);
while($row=mysqli_fetch_array($select))
{
echo "<option value='".$row['sno']."'>".$row['state_list']."</option>";
}
?>
</select>
</div>
</div>
<!-- <div class="col-md-1"></div> -->
<div class="col-md-3">
<div class="form-group">
<select name="" class="custom-select" id="city_dropdown">
</select>
</div>
</div>
</div>
This is city_state.php from where we will get date when user select state in main page
<?php
include("scripts/settings_dbase.php");
?>
<?php
//require_once "db.php";
$state_id = $_POST["state_id"];
echo $state_id;
$sql="SELECT * FROM city_name where parent_state = '".$state_id."'";
echo $sql;
$result=execute_query($sql);
?>
<option value="">Select City</option>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row["sno"];?>"><?php echo $row["city_name"];?></option>
<?php
}
?>
No comments:
Post a Comment