How to Create Dynamic Dependent select box using ajax

You need a dynamic dependent select box. We will explain how to create a dynamic dependent select box in PHP, jquery and ajax.

index.php

<?php
include_once 'dbconfig.php';
?>
<html>
<head>
<title>Dynamic Dependent Select Box using Ajax</title>
<script type="text/javascript" src="jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
	$("#loding1").hide();
	$("#loding2").hide();
	$(".country").change(function()
	{
		$("#loding1").show();
		var id=$(this).val();
		var dataString = 'id='+ id;
		$(".state").find('option').remove();
		$(".city").find('option').remove();
		$.ajax
		({
			type: "POST",
			url: "get_state.php",
			data: dataString,
			cache: false,
			success: function(html)
			{
				$("#loding1").hide();
				$(".state").html(html);
			} 
		});
	});
	
	
	$(".state").change(function()
	{
		$("#loding2").show();
		var id=$(this).val();
		var dataString = 'id='+ id;
	
		$.ajax
		({
			type: "POST",
			url: "get_city.php",
			data: dataString,
			cache: false,
			success: function(html)
			{
				$("#loding2").hide();
				$(".city").html(html);
			} 
		});
	});
	
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
div
{
	margin-top:100px;
}
select
{
	width:200px;
	height:35px;
	border:2px solid #456879;
	border-radius:10px;
}

.color {
	color:green;
}

.link {
	color:red;
}
</style>
</head>

<body>
<h1 align="center" class="color"> Daynamic Dropdown in PHP &MySql Ajax And jQuery</h1>
<center>
<div>
<label>Country :</label> 
<select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
	$stmt = $DB_con->prepare("SELECT * FROM country");
	$stmt->execute();
	while($row=$stmt->fetch(PDO::FETCH_ASSOC))
	{
		?>
        <option value="<?php echo $row['country_id']; ?>"><?php echo $row['country_name']; ?></option>
        <?php
	} 
?>
</select>
<br><br><br>
<label>State :</label> 
<select name="state" class="state">
<option selected="selected">--Select State--</option>
</select>
<img src="ajax-loader.gif" id="loding1"></img>
<br><br><br>
<label>City :</label> 
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
<img src="ajax-loader.gif" id="loding2"></img>
<br><br><br>
</div>
<br />
</center>
</body>
</html>

dbconfig.php

<?php

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "database";

try
{
	$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
	$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
	$e->getMessage();
}

get_city.php

<?php
include('dbconfig.php');
if($_POST['id'])
{
	$id=$_POST['id'];
	
	$stmt = $DB_con->prepare("SELECT * FROM city WHERE state_id=:id");
	$stmt->execute(array(':id' => $id));
	?><option selected="selected">Select City :</option>
	<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
	{
		?>
		<option value="<?php echo $row['city_id']; ?>"><?php echo $row['city_name']; ?></option>
		<?php
	}
}
?>

get_state.php

<?php
include('dbconfig.php');
if($_POST['id'])
{
	$id=$_POST['id'];
		
	$stmt = $DB_con->prepare("SELECT * FROM state WHERE country_id=:id");
	$stmt->execute(array(':id' => $id));
	?><option selected="selected">Select State :</option><?php
	while($row=$stmt->fetch(PDO::FETCH_ASSOC))
	{
		?>
        	<option value="<?php echo $row['state_id']; ?>"><?php echo $row['state_name']; ?></option>
        <?php
	}
}
?>

Check on Facebook

44 thoughts on “How to Create Dynamic Dependent select box using ajax”

  1. Do you mind if I quote a few of your articles as long as I provide credit andd sources back
    to your weblog? My blog site iss in the very same area oof interest as yours annd my visitors would certainly benefit from a lot of the
    information youu provide here. Please let me know iff this okay
    with you. Cheers!

    Reply
  2. I blog quite often and I really thank you for your content.
    This great article has truly peaked my interest. I
    will bookmark your blog and keep checking for new details about
    once a week. I opted in for your Feed too.

    Reply
  3. I’ve read some excellent stuff here. Certainly value bookmarking for revisiting.
    I wonder how a lot effort you set to make the sort of great informative web site.

    Reply
  4. Thank you for any other wonderful post. Where else could anyone get that kind
    of information in such an ideal approach of writing?
    I’ve a presentation subsequent week, and I’m on the look for such info.

    Reply
  5. With havin so much content do you ever run into any problems of plagorism or copyright infringement?
    My site has a lot of exclusive content I’ve either written myself or outsourced but it
    looks like a lot of it is popping it up all over the
    internet without my authorization. Do you know any solutions to help stop
    content from being ripped off? I’d really appreciate
    it.

    Reply
  6. Hello There. I found your blog using msn. This is a really well written article.
    I’ll make sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I will certainly return.

    Reply
  7. The other day, while I was at work, my cousin stole my iphone and tested to see if it
    can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad
    is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!

    Reply
  8. My partner and I stumbled over here different page and thought
    I might as well check things out. I like what I see so
    now i’m following you. Look forward to exploring your
    web page repeatedly.

    Reply
  9. Massage therapy promotes tissue regeneration and is also a terrific way to
    cure acne, or even acne scars as well. When you visit a spa, the decisions about how you will spend your time
    and energy are often left for you but you could be wise to
    make a choice of these packages that incorporate numerous
    services from facials to mineral baths. Again, this process
    isn’t for anyone but should you prefer to wash your own personal sheets, this is the way
    you can keep them who is fit for a time.

    Reply
  10. Its like you learn my thoughts! You appear to grasp so
    much approximately this, such as you wrote the guide in it or something.
    I feel that you can do with a few p.c. to drive the message house a little
    bit, but other than that, this is great blog. A great read.
    I’ll definitely be back.

    Reply
  11. Undeniably believe that which you stated. Your favorite justification appeared to be on the internet the easiest thing to be aware of.
    I say to you, I certainly get irked while people think about worries that they just don’t know about.
    You managed to hit the nail upon the top and defined out
    the whole thing without having side-effects ,
    people can take a signal. Will probably be back to get more.
    Thanks

    Reply
  12. I know this if off topic but I’m looking into starting my own weblog
    and was wondering what all is needed to get set up?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% positive. Any
    recommendations or advice would be greatly
    appreciated. Many thanks

    Reply
  13. Hello there, just became aware of your blog through Google, and
    found that it’s truly informative. I’m going
    to watch out for brussels. I’ll be grateful if you continue this in future.
    Many people will be benefited from your writing.
    Cheers!

    Reply
  14. It’s perfect time to make some plans for the
    future and it is time to be happy. I’ve read this post and if I could I wish to suggest you few interesting things or advice.
    Perhaps you can write next articles referring to this
    article. I desire to read even more things about it!

    Reply
  15. Howdy just wanted to give you a quick heads up. The text in your article seem to be running off the screen in Safari.
    I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I thought I’d post
    to let you know. The layout look great though! Hope you get the
    problem fixed soon. Cheers

    Reply
  16. It’s a shame you don’t have a donate button! I’d definitely
    donate to this brilliant blog! I guess for
    now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to new updates and will share this site with my Facebook group.
    Chat soon!

    Reply
  17. Attractive element of content. I just stumbled upon your blog and in accession capital to claim that I get actually loved account your weblog posts.

    Any way I’ll be subscribing for your feeds or even I fulfillment you get right of entry to constantly quickly.

    Reply

Leave a Comment