PHP Ajax Dependent Dropdown List Example
In this post, i am going to share with you how to make dynamic dependent dropdown list using jquery ajax with php MySQL. In this simple example through we understand how to work dependent dropdown in core PHP even if you beginner. I also posted for php laravel framework How to make simple dependent dropdown using jquery ajax in Laravel 5?.
We sometimes require to make dependent dropdown like when state select at that time bellow city drop down list should change, i mean related to selected state. In this example i have two tables and there are listed bellow:
1.demo_state
2.demo_cities
So, when user will change state at that time, dynamically change city drop down box from database. you can implement this example in your application by follow bellow few step.
Step 1: Create Tables and Dummy Data
In first step we require to create database and tables for dependent dropdown example. So first you require to create "test" database in your phpmyadmin. After created database successfully we require to create two new table "demo_state" and "demo_cities" using following bellow SQL Query.
demo_state table:
CREATE TABLE `demo_state` (
`id` int(11) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
demo_cities table:
CREATE TABLE `demo_cities` (
`id` int(11) NOT NULL,
`state_id` int(12) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Now, in your database, you will have two tables "demo_state" and "demo_cities". Now we require to add some dummy data in both table like as bellow image.
demo_state
demo_cities
Step 2: Create index.php file
In this step we will create index.php file, in this file we write code for state drop-down and city drop-down. In this file layout will display so put bellow code on index.php file.
index.php
<!DOCTYPE html>
<html>
<head>
<title>PHP - How to make dependent dropdown list using jquery Ajax?</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Select State and get bellow Related City</div>
<div class="panel-body">
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" class="form-control">
<option value="">--- Select State ---</option>
<?php
require('db_config.php');
$sql = "SELECT * FROM demo_state";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" class="form-control" style="width:350px">
</select>
</div>
</div>
</div>
</div>
<script>
$( "select[name='state']" ).change(function () {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: "ajaxpro.php",
dataType: 'Json',
data: {'id':stateID},
success: function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
</script>
</body>
</html>
Step 3: Add DB Configuration File
Now we require to create db configuration file for database, that way you can set username, password, database and host. So let's create db_config.php file and put bellow code:
db_config.php
<?php
define (DB_USER, "root");
define (DB_PASSWORD, "root");
define (DB_DATABASE, "test");
define (DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>
Step 4: Add Ajax File
In last step, we need to create ajax pro file, in this file we write code for dynamic ajax city drop-down json data. So let's create ajaxpro.php file and put bellow code:
ajaxpro.php
<?php
require('db_config.php');
$sql = "SELECT * FROM demo_cities
WHERE state_id LIKE '%".$_GET['id']."%'";
$result = $mysqli->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[$row['id']] = $row['name'];
}
echo json_encode($json);
?>
Ok, now we are ready to run our example. So let's run bellow command on your root directory for quick run:
php -S localhost:8000
Now you can open bellow URL on your browser:
http://localhost:8000
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- PHP CURL Post Request with Parameters Example
- PHP Ajax Multiple Image Upload with Preview Example
- PHP MySQL Image Gallery CRUD Example
- Laravel Sub-Domain Wise Routing File Example
- PHP Bootstrap Autocomplete Tokenfield using Ajax Example
- Tags Input with Autocomplete using jQuery and PHP Example
- Laravel Ajax Image Upload with Validation Example
- PHP Capture Screenshot of Website from URL Example
- Laravel Dynamic Dependent Dropdown Example
- PHP Crop Image Before Upload using Croppie JS Example
- PHP JQuery Select2 Ajax Autocomplete Example
- How to Remove Duplicate Values from Array in PHP?
- How to Get File Name without Extension in PHP?
- Display Loading Image when AJAX Call is in Progress Example