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.
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> <label>Select State</label> <select name="state" id="state" onchange="load_options(this.value,'city');"> <option value="">Select state</option> </select> <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
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
Are you not getting the output properly now?
can u tell me how i make depandent select boxes with out database or on change select event how i replace the currents contects plz help me i shall send u an example http://dekho.com.pk/new
Without on change it is not possible but you can do one thing. You can attach the change event to a select list on document ready like below:
$(“#yourselectlistid”).live(‘change’,function(){
write your code which fills out the select list content with any array if you don’t want to use database.
});
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
Add the name attributes to all your select lists and get the values by that for e.g. to get country value you use $country = $_POST['country'];
By the way I’ve updated the code. You can see it.
The same in PDO will be great !
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()
The same code can be used in your situation also.
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!
I’m not understanding your problem. Could you elaborate it more….
Of course
Your code is like that: (line 45-61)
Select Country
Select country
Select State
Select state
Select city
Select City
My code is like that:
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.
pfff..The code does not appear. how can I send you my code?
send at [email protected]
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
as you are talking about tomcat. Are you making your project in jsp or php?
I need result instead of the third combobox, a textbox, I could help?
Can you help me?, I need to have 2 combobox, and that the result comes out in a text, thanks
I’m also trying to do that. Have you found any solution?
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.
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
What kind of error you’re seeing here???? could you please elaborate it??????
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.
and call a function onchange=”load_options(this.value,’pin_code’);” on city select box.
thanks sir for your reply
but i want to display on table format…and not only pincode….i want to display….state Name, District, Post_office, pincode…
all display on table format not in combobox
thanks
sujeet thakur
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.
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.
hoW CAN I USE IT IN JUST FOR ONE COUNTRY viz. INDIA?
hii…this blog is very useful for me..thanks alot.
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.
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.
thank you sir it really helpful to me
A Very helpful tutorial.Working nicely for me.Thanks.
above code run but country is not display in browser your sql file where put ?
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.
Thanks
select->this’.index’
$entity name
those two alone display in country select
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
hi sir
how use this code for utf-8 charset ?
please help me
thanks