Dynamic Dependent Select Box using jQuery, Ajax and PHP

We are going to do  dynamic dependent select box with PHP. Based on Jquery and Ajax request, we are going to explain the dynamic dependent multiple select boxes using jQuery, Ajax, PHP and MySQL.

The dynamic dependent select box is mostly used for country state city dropdown. In this tutorial we will create a relational select box with country and their state and city similarly.

At first, the country dropdown will be displayed with all countries and when a country would be chosen , the respective state would be fetched from mysql database and similarly when we select state, City would be fetched from mysql.

Database & Tables

Create a database, like ajax. ajax consists of three tables country, state, and city. state table has a relation with country table and city table has a relation with state table.

countries state and city Table:
This table contains all the countries,state,city  data. you can run this sql query to import all three tables to your ajax database.

-- phpMyAdmin SQL Dump
-- version 3.5.2.2
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 04, 2017 at 01:54 PM
-- Server version: 5.5.27
-- PHP Version: 5.4.7

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `ajax`
--

-- --------------------------------------------------------

--
-- Table structure for table `city`
--

CREATE TABLE IF NOT EXISTS `city` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(56) NOT NULL,
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`id`, `name`, `state_id`, `country_id`) VALUES
(1, 'New Delhi', 1, 1),
(2, 'Gurugram', 2, 1),
(3, 'Mumbai', 4, 1),
(4, 'Kanpur', 3, 1),
(5, 'Nagpur', 4, 1),
(6, 'Pune', 4, 1),
(7, 'Lucknow', 3, 1),
(8, 'Varanasi', 3, 1),
(9, 'Faridabad', 2, 1),
(10, 'Ambala', 2, 1),
(11, 'Patna', 5, 1),
(12, 'Khagaria', 5, 1),
(13, 'Bhagalpur', 5, 1),
(14, 'Munger', 5, 1),
(15, 'Ranchi', 6, 1),
(16, 'Jamshedpur', 6, 1),
(17, 'Islamabad', 7, 2),
(18, 'Sialkot', 9, 2);

-- --------------------------------------------------------

--
-- Table structure for table `country`
--

CREATE TABLE IF NOT EXISTS `country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(56) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`id`, `name`) VALUES
(1, 'India'),
(2, 'Pakistan');

-- --------------------------------------------------------

--
-- Table structure for table `state`
--

CREATE TABLE IF NOT EXISTS `state` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(56) NOT NULL,
  `country_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`id`, `name`, `country_id`) VALUES
(1, 'Delhi', 1),
(2, 'Haryana', 1),
(3, 'Uttar Pradesh', 1),
(4, 'Maharashtra', 1),
(5, 'Bihar', 1),
(6, 'Jharkhand', 1),
(7, 'Islamabad ', 2),
(8, 'Sindh ', 2),
(9, 'Punjab ', 2);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

database and tables are ready to use !

Now we are going to create a page called index.php. here we implement the jquery script and ajax.

<?php include_once 'connect.php'; 

$cnt="select * from country";
$cntq=mysql_query($cnt);
?>
<!DOCTYPE html>


<html>
<head>
<title>Divson.in</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h3>Dynamic dependent select box using ajax:</h3>
<!-- Required Div Starts Here -->
<form id="form" name="form">
<h4>Divson.in</h4>
<div>
<label>Select Country :</label>
<select name="country" id="country" class="form-control">
<option value="">Select Country</option>
<?php while($country=mysql_fetch_assoc($cntq)){ ?>
<option value="<?php echo $country['id'];?>"><?php echo $country['name'];?></option>	
<?php } ?>
</select>
<br>
<label>Select State :</label>
<select name="state" id="state" class="form-control">
<option value="">Select State</option>
</select>
<br>
<label>Select City :</label>
<select name="city" id="city" class="form-control">
<option value="">Select City</option>
</select>

</div>
</form>
<div id="clear"></div>
</div>
<div id="clear"></div>
</div>
</body>
</html>

<script>
 $('#country').on('change',function(){
        var country_id = $(this).val();
            $.ajax({
                type:'GET',
                url:'state.php?country_id='+country_id,
                success:function(html){
                    $('#state').html(html);
                }
            }); 
        });
    
	
$('#state').on('change',function(){
        var state_id = $(this).val();
		var country_id = $('#country').val();
            $.ajax({
                type:'GET',
                url:'city.php?country_id='+country_id+'&state_id='+state_id,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        });
</script>

we need to 2 more pages to create 1 for city and 1 for state, so that we can fetch the record of state and city on the basis of their respective country : city.
both pages will be requested by ajax call .

<?php include_once 'connect.php'; 
$id=$_GET['country_id'];

$st="select * from state where country_id='$id'";
$stq=mysql_query($st);

 echo '<option value="">Select state</option>';
 while($data = mysql_fetch_assoc($stq)){ 
            echo '<option value="'.$data['id'].'">'.$data['name'].'</option>';
        }
?>

similarly for city, we are going to create a city.php this is also requested by ajax call in jquery script .

<?php include_once 'connect.php'; 
$country_id=$_GET['country_id'];
$state_id=$_GET['state_id'];

$st="select * from city where state_id='$state_id' and country_id='$country_id'"; 
$stq=mysql_query($st);

echo '<option value="">Select City</option>';
while($data = mysql_fetch_assoc($stq)){ 
echo '<option value="'.$data['id'].'">'.$data['name'].'</option>';
}
?>

All Set now ! i hope this will be work fine in your case. i have also attached the demo source file for your convenience and for demo purpose.

Click here to Download Source code.



Author: Gautam Jha
I am Gautam Jha from New Delhi, India. I love to write code and blogs, traveling, Video games, sometimes study as well.

Leave a Reply

Hey there!

Sign in

Forgot password?
Close
of

Processing files…