Country, State, City Dynamic Dependent Select Box using Jquery and Ajax

Country, State, City Dynamic Dependent Select Box using Jquery and Ajax

Every online registration form always has three basic dropdowns Country, State and City. Making these dropdowns dependent on each other is a headache of most of the people. To overcome this problem I’ve designed a very simple and useful script using Jquery, Ajax and php. The project has one php and one html file with some css and javascript snnipet. You just have to make a database and import the sql file given in the download package. Change the database properties in ajax.php file accordingly.

Country, State, City Dynamic Dependent Select Box using Jquery and Ajax

MCountry, State, City Dynamic Dependent Select Box using Jquery and Ajax

Ajax.php

<?php
	/* File : ajax.php
	 * Author : Manish Kumar Jangir
	*/
	class AJAX {

		private $database = NULL;
		private $_query = NULL;
		private $_fields = array();
		public  $_index = NULL;
		const DB_HOST = "localhost";
		const DB_USER = "root";
		const DB_PASSWORD = "";
		const DB_NAME = "csc";

		public function __construct(){
			$this->db_connect();					// Initiate Database connection
			$this->process_data();
		}

		/*
		 *  Connect to database
		*/
		private function db_connect(){
			$this->database = mysql_connect(self::DB_HOST,self::DB_USER,self::DB_PASSWORD);
			if($this->database){
				$db =  mysql_select_db(self::DB_NAME,$this->database);
			} else {
				echo mysql_error();die;
			}
		}

		private function process_data(){
			$this->_index = ($_REQUEST['index'])?$_REQUEST['index']:NULL;
			$id = ($_REQUEST['id'])?$_REQUEST['id']:NULL;
			switch($this->_index){
				case 'country':
					$this->_query = "SELECT * FROM countries";
					$this->_fields = array('id','country_name');
					break;
				case 'state':
					$this->_query = "SELECT * FROM states WHERE country_id=$id";
					$this->_fields = array('id','state_name');
					break;
				case 'city':
					$this->_query = "SELECT * FROM cities WHERE state_id=$id";
					$this->_fields = array('id','city_name');
					break;
				default:
					break;
			}
			$this->show_result();
		}

		public function show_result(){
			echo '<option value="">Select '.$this->_index.'</option>';
			$query = mysql_query($this->_query);
			while($result = mysql_fetch_array($query)){
				$entity_id = $result[$this->_fields[0]];
				$enity_name = $result[$this->_fields[1]];
				echo "<option value='$entity_id'>$enity_name</option>";
			}
		}
	}

	$obj = new AJAX;

?>

index.html

<html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11">
<head>
<title>Country State City Dependent Dropdown using Ajax</title>
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>
<style type="text/css">
body{
	font-family:arial;
	color:#666;
}
form select{
	padding:5px;
	border:1px solid #aaa;
	border-radius:4px;
	width:120px;
}

form label{
	font-size:12px;
	font-weight:bold;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
	load_options('','country');
});

function load_options(id,index){
	$("#loading").show();
	if(index=="state"){
		$("#city").html('<option value="">Select city</option>');
	}
	$.ajax({
		url: "ajax.php?index="+index+"&id="+id,
		complete: function(){$("#loading").hide();},
		success: function(data) {
			$("#"+index).html(data);
		}
	})
}
</script>
</head>
<body>
<div style="width:800px; margin:auto;padding-top:100px;">
<h1>Country,State,City dynamic dependent dropdown using Ajax and Jquery</h1>
<form>
		<label>Select Country</label>
		<select name="country" id="country" onchange="load_options(this.value,'state');">
			<option value="">Select country</option>
		</select>
		&nbsp;&nbsp;&nbsp;
		<label>Select State</label>
		<select name="state" id="state" onchange="load_options(this.value,'city');">
			<option value="">Select state</option>
		</select>
		&nbsp;&nbsp;&nbsp;
		<label>Select city</label>
		<select name="city" id="city">
			<option value="">Select City</option>
		</select>
		<img src="loader.gif" id="loading" align="absmiddle" style="display:none;"/>
</form>
</div>
</body>
</html>

Click on download button to get this small project

41 Responses to “Country, State, City Dynamic Dependent Select Box using Jquery and Ajax”
  1. Hi I had tried (“Country, State, City Dynamic Dependent Select Box using Jquery and Ajax”) Program using all the search results but it got a mistake and I didn’t get the output but your Article was very good and at the first time i got the output Thank you very much for the team Members of Blogaddition

  2. trevwatson says:

    Manish,
    Thanx for your tutorial…. I trawled for a long time to get something a novice like me could understand. Following your tut I have successfully built and populated the dropdown menus.

    The next step I am lost on. How do I get the values from the dropdown box selections and use them in POST data to send the user to the relevant page? I even can’t seem to get the values into some php variables and echo them…. If this question makes me look like a newb, then it’s because I am.

    any help (or links to help) greatly appreciated.
    cheers from Trevor

  3. Rsport says:

    The same in PDO will be great !

  4. alan says:

    Hi,
    Great tut thank you.

    I have one problem. What if i have database when table cities have names in 4 column(`id`, `state_id`, ‘some_cell’,`city_name`) and table states hav names in 5 column (`id`, `country_id`,’some_cell_1′,’some_cell_2′, `state_name`);

    How write public function show_result()

  5. Maria says:

    Manish, Thanks very much for your tutorial.
    After many hours I was able to receive response from my code.
    I have a question. I am using a code like yours, but I have another one tag in my HTML with two dropdown menus. This tag provoked a double call of the onchange event at the same time. As a result, the second tag does not show any options. Do you know what can I do for that?
    Thanks in advance!

  6. Maria says:

    I am sorry for the last reply. It was send by a mistake :)

    My code is like yours (lines 45-61).
    I also have some code witch is like the following :
    63
    64 Select Country
    65
    66 Select country
    67
    68
    69 Select State
    70
    71 Select state
    72
    73
    The dropdown menus (lines 63-73) do not show any options.
    Is there any solution about that?

    For any clarifications just let me know.

  7. Anirban says:

    Hello

    I have downloaded your code …i have created database in mysql ….but i cant fetch the necessary values from it for ex- select country isnt coming .Also do specify how to run the code i mean do u have to deploy that to tomcat ???please revert back fast

  8. Chuy says:

    I need result instead of the third combobox, a textbox, I could help?

  9. shravan says:

    hi, nice post, I have a small requirement, need to display service centers in a based on State and City. Can you please suggest please.

    • 1. Make an additional table in your database “service_centers” with three collums ‘id’,'city_id’,service_center_name’ and make some entry in this table according to your city and center name.
      2. Make a copy of city code in both index.html and ajax.php and replace city with service_center_name.
      3. call onchange=”load_options(this.value,’service_center’);” on city select list.

  10. hi ,when i run ur program it is not enerating item.For example in select country der r no items in it.How ever when i run only ajax.php files it showing errors.please help me

  11. hello sir,
    i am sujeet. i see your script and use it on my webstie. that is work supurb. sir one think i want …i want to show my result when i click my last combobox option. like when i select city….than all postoffice with pincode apper on my webpage. but sir i dont know how to display data. sir please help me.

  12. Thank u manish it is working ,now my problem is i want to generate a country code in a text box on selection of country.
    Example if a user selects india,than a country code 91 should b generated.I tryed but i am getting run time error.

  13. says:

    Thank you manish it is working ,now my problem is i want to generate a country code in a text box on selection of country.
    Example if a user selects india,than a country code 91 should b generated.I tryed but i am getting run time error.

  14. hoW CAN I USE IT IN JUST FOR ONE COUNTRY viz. INDIA?

  15. sucharitha says:

    hii…this blog is very useful for me..thanks alot.

  16. derek says:

    Hi, Thank you for this, it is very helpful. I am trying to display data within the html once they select the last dropdown.

    For cars, I have dropdowns
    -make
    -model
    -category
    -year.

    I am trying to figure out how to display the results into a div called once someone selects the last year. Instead of displaying into another drop-down, wanted to display in the middle section of the page just the results for the cars selected.

    • derek says:

      Never mind, I figured that out. Currently the only problem I am stuck on is getting the correct year. currently how it is set up, it will only get the year for all the categories in the database. I need to get the year for the selected category for the selected model. Any suggestions would be much appreciated.

  17. ASHISH says:

    thank you sir it really helpful to me

  18. deshan says:

    A Very helpful tutorial.Working nicely for me.Thanks.

  19. harpalsinh says:

    above code run but country is not display in browser your sql file where put ?

  20. Nimesh says:

    Hi,
    I would like this to work with an existing database of continents, countries and state. I changed the code accordingly but it does not work then.

    Also, for the state, I would like it to work so that the user can enter a new entry if the relevant state is not mentioned. This is because the state will not be populated from a master list as such.

    Also, please let me know if this code will work with Twitter Bootstrap?

    Please help.

    Thanks.

  21. says:

    select->this’.index’
    $entity name

    those two alone display in country select

  22. Rajeev says:

    Hi Manish, thanks for sharing the script. It works fine. I am using it to submit data to a database but it instead of the names of the cities or countries, it stores their respective “id” as a numeric value. Can you suggest something so that it stores the name of the country, state or city as a value in the respective field rather than the ‘id’. Many thanks

  23. nima says:

    hi sir
    how use this code for utf-8 charset ?
    please help me
    thanks