Step1:- We need to be create the database and table for example.
City Table:-
INSERT INTO `state_tb` (`sid`, `sname`, `cid`) VALUES (NULL, 'Utter Pradesh', '1'), (NULL, 'Maharashtra', '1'), (NULL, 'Rajasthan', '1'),(NULL, 'Madhya Pradesh', '1'), (NULL, 'Balochistan', '2'), (NULL, 'Punjab', '2'), (NULL, 'Sindh', '2')
dependency.php
<h2>PHP Ajax Dropdown Dependency Show State And City</h2>
<form>
<label>Country : </label>
<select id="country">
<option value="">Select Country</option>
</select>
<br><br>
<label>State : </label>
<select id="state">
<option value=""></option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function loadData(type, c_id) {
$.ajax({
url : "select.php",
type : "POST",
data : {type : type, id : c_id},
success : function(data){
if(type == "stateData") {
$('#state').html(data);
}
else{
$('#country').append(data);
}
},
});
}
loadData();
$("#country").on('change', function(){
var country = $("#country").val();
if(country != "") {
loadData("stateData", country);
}else{
$('#state').html("");
}
});
});
</script>
Step 3: Now, update the following PHP form into select.php file:
select.php
$conn = mysqli_connect("localhost", "root", "", "test");
if($_POST['type'] == "") {
$sql = "SELECT * FROM country_tb";
$query = mysqli_query($conn,$sql) or die("Query Unsuccessful.");
$str = "";
while ($row = mysqli_fetch_assoc($query)){
$str .= "<option value='{$row['cid']}'>{$row['cname']}</option>";
}
}else if($_POST['type'] == "stateData"){
$sql = "SELECT * FROM state_tb WHERE cid = {$_POST['id']}";
$query = mysqli_query($conn,$sql) or die("Query Unsuccessful.");
$str = "";
while ($row = mysqli_fetch_assoc($query)){
$str .= "<option value='{$row['sid']}'>{$row['sname']}</option>";
}
}
echo $str;
No comments:
Post a Comment
If you have any problem please let me know.