Dynamic Dependent Select Box using jQuery and Ajax

We often see dynamic dependent select box in website, which are part of web form. Today i will share how to use dynamic dependent select box using jQuery and ajax. I will use an example of country and city, when you will select any country, its cities will be available in the below select box without refresh or reload the page this is the power of Ajax.

Steps to Create Dynamic Dependent Select Box using jQuery and Ajax

Create a Database

Create Two Tables of County and City and Insert Data in Both Table

Create a Database Connection File

Create Index File Which Using JQuery and Ajax

Create PHP Action File

1. Create a Database

Create a database with name parent_child_select. For this purpose run the following query in MySQL.

1

CREATEDATABASEparent_child_select;

2. Create Two Tables of County and City and Insert Data in Both Table

Create two tables with name county and city and insert sample data in database by using the following queries. For your ease i have also attached the SQL file in download file just import this file in SQL and it will create tables with sample data.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

CREATETABLEIF NOT EXISTS`country`(

`country_id`int(11)NOT NULLAUTO_INCREMENT,

`country_name`varchar(50)NOT NULL,

PRIMARY KEY(`country_id`)

);

CREATETABLEIF NOT EXISTS`city`(

`city_id`int(11)NOT NULLAUTO_INCREMENT,

`city_name`varchar(50)NOT NULL,

`country_id`varchar(50)NOT NULL,

PRIMARY KEY(`city_id`)

);

INSERTINTO`city`(`city_id`,`city_name`,`country_id`)VALUES

(1,'Karachi','1'),

(2,'Lahore','1'),

(3,'Jeddah','2'),

(4,'Riyadh','2'),

(5,'London','3'),

(6,'Liverpool','3');

INSERTINTO`country`(`country_id`,`country_name`)VALUES

(1,'Pakistan'),

(2,'Saudi Arabia'),

(3,'United Kingdom');

3. Create a Database Connection File

Create a file with name db.php and copy paste the below code in that file. Make sure that you changed your database, username, password and host.

1

2

3

4

5

6

7

8

9

10

<?php

// Enter your Host, username, password, database below.

// I left password empty because i do not set password on localhost.

$con=mysqli_connect("localhost","root","","parent_child_select");

// Check connection

if(mysqli_connect_errno())

{

echo"Failed to connect to MySQL: ".mysqli_connect_error();

}

?>

4. Create Index File Which Using JQuery and Ajax

Create a file with name index.php and copy paste the below code in this file. Note that I have added the jQuery and Ajax script in the footer of this file.

Readers also read

15 Comments

Hi there,
great tutorial! i’m having trouble implemented the last section. Once I choose an option from the first drop down box, the second drop down box goes completely blank, even removing the original default text. I have tried debugging this for many days and I have managed to find out that the problem lies in the AJAX file. For some reason it appears that I can’t connect to any sql server from the ajax file.
-I can connect to the ajax file fine as I can test
$id=$_POST[‘id’];
if($id==1){
echo “Selected item 1″;
and it works fine.
However, I can’t get any results to populate from my database. Do you know what I can do to continue debugging, or do you know what my problem could be? The sql query works fine in phpmyadmin, and the same query (with echo results) work fine in my index.php for the first option. As you can tell, this is very confusing!

I will suggest you that you just download my tutorial from the above download link and if you are using xampp then place the downloaded folder in it and make database connection changes and then test if it is working in your side or not. It should be working, make sure that you create a separate folder as i said, if you will try to use Ajax inside any other CMS may be it will not work, like WordPress have other requirements to work on Ajax, therefore first try my sample demo file on your host.

Hi, Thank you for a really quick reply.
Your demo seems to be working just fine. I tried using your demo as a starting point, changing your sql values to the ones in my database. Still no luck though! The query works just fine in index.php, but it seems I can’t even make a connection when accessing the database through ajax using my own credentials. I even tested the connection:
if($con){
echo ‘Connected’; };
else {
echo ‘Not Connected’>;
If the database connected, when I select my first dropdown bar (that works perfectly fine), the dropdown bar will read either not connected, or connected. Each time the bar will always say that there is no connection being made. I have no idea how this is an issue as your demo worked perfectly fine! Thanks for your suggestions though!

Well you can see that i made one db.php file and i call it on both pages, index.php and ajax.php so if your database connection is working fine on your index.php it should be working on your other page as well because this is same file. I think there may be some other issue, I prefer that you try to read my script again, may be you are facing issue because of some other reason.

hello Rehman, thank you for this article. I needed to change country for district and city for villages as it applies to my project and the script will not load the villages when i select a district. Please how can i get some help?

This is not easy as you can not find data easily all list of streets of all countries, however you will need to create another table for street with fields name something like this street_id, street_name and city_id.
And on ajax part also check if city is selected populate all street values in dependent field same as we did for city. Hope this help you.

to also load the streets when a city is selected, can i add this to the ajax page?
<?php
include('db.php');
if($_POST['id']){
$id=$_POST['id'];
if($id==0){
echo "Select City”;
}else{
$sql = mysqli_query($con,”SELECT * FROM city WHERE country_id=’$id'”);
while($row = mysqli_fetch_array($sql)){
echo ”.$row

I would suggest you to use different field name in html select box and also in php script, if you use id for two select boxes then you will face duplicate issue, you can use city_id and check if city_id is set in PHP script then show street, you will also need to change it in Ajax script. Simply replace id with city_id on every call such as Ajax, Select box, and PHP script.

Step 3 is only database connection, as we always need to create database connection if we want using data from database, you can search about it in details in Google if you do not have any idea about database and its connection.