This tutorial will you help to populate a dropdown list based on selection of another dropdown option using ajax. What actually we do here, let’s assume we have two dropdown list in a form. The first dropdown list is the list of countries where users can select one country. The second dropdown list will display only the states it belongs to the selected country dynamically through ajax means no page refreshing.
Also, you can enjoy the live demo example on Populate a dropdown list based on selection of another dropdown list using ajax for better understanding. As well as you can get the full source code from the download link.
If you want to generate or populate multiple dropdown lists using Ajax then click on the following article — Populate multiple dropdown lists using Ajax, jQuery, PHP, and MySQL.
Database Tables
- CREATE TABLE `countries` (
- `id` int(11) NOT NULL,
- `country` varchar(255) NOT NULL
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
- CREATE TABLE `states` (
- `id` int(11) NOT NULL,
- `country_id` int(11) NOT NULL COMMENT 'id of the countries table',
- `state` varchar(255) NOT NULL
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
- INSERT INTO `countries` (`id`, `country`) VALUES
- (1, 'India'),
- (2, 'America');
- INSERT INTO `states` (`id`, `country_id`, `state`) VALUES
- (2, 1, 'West Bengal'),
- (3, 1, 'Maharastra'),
- (4, 1, 'Goa'),
- (5, 1, 'Kerala'),
- (6, 2, 'Newyork'),
- (7, 2, 'Ohio'),
- (8, 2, 'Texas');
For dynamically populate or generate the dropdown list using ajax, you need two tables in the database. The above queries will create two tables and insert some data into these two tables respectively.
Database Connection (db.php)
- <?php
- define('HOSTNAME','localhost');
- define('DB_USERNAME','username');
- define('DB_PASSWORD','password');
- define('DB_NAME', 'database-name');
- //global $con;
- $con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
- // Check connection
- if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
- ?>
Establishing a database connection using PHP is an important part of this example. Replace username, password, and database-name with your credentials.
HTML – Dynamically Populate Dropdown List Using Ajax (index.php)
Let’s follow the below code which lets you help to dynamically generate the dropdown list using ajax.
- <script type="text/javascript" src="jquery.min.js"></script>
- <script type="text/javascript" src="ajax.js"></script>
- <?php include("db.php");?>
- <div class="">
- <label>Country :</label>
- <select name="country" id="country">
- <option value=''>------- Select --------</option>
- <?php
- $sql = "select * from `countries`";
- $res = mysqli_query($con, $sql);
- if(mysqli_num_rows($res) > 0) {
- while($row = mysqli_fetch_object($res)) {
- echo "<option value='".$row->id."'>".$row->country."</option>";
- }
- }
- ?>
- </select>
- <label>State :</label>
- <select name="state" id="state"><option>------- Select --------</option></select>
- </div>
As you can see above, we created two dropdown list. The first dropdown list is for the country list which is dynamic and it comes from the database during the page load by using a simple PHP code. The second dropdown list will dynamically generate the list of states based on the selection of the country dropdown list using Ajax and PHP.
Ajax Call – Create Dynamic dropdown (ajax.js)
- $(document).ready(function() {
- $("#country").change(function() {
- var country_id = $(this).val();
- if(country_id != "") {
- $.ajax({
- url:"get-states.php",
- data:{c_id:country_id},
- type:'POST',
- success:function(response) {
- var resp = $.trim(response);
- $("#state").html(resp);
- }
- });
- } else {
- $("#state").html("<option value=''>------- Select --------</option>");
- }
- });
- });
When you first select or change any country from the first dropdown list the $(“#country”).change(function() {….}) will come into action. Variable country_id holds the id of the selected country. If it is not null then $.ajax({….}) will send an Ajax post request to the get-states.php page with the country id.
Fetch The List Of The States (get-states.php)
- <?php include("db.php"); ?>
- <?php
- if(isset($_POST['c_id'])) {
- $sql = "select * from `states` where `country_id`=".mysqli_real_escape_string($con, $_POST['c_id']);
- $res = mysqli_query($con, $sql);
- if(mysqli_num_rows($res) > 0) {
- echo "<option value=''>------- Select --------</option>";
- while($row = mysqli_fetch_object($res)) {
- echo "<option value='".$row->id."'>".$row->state."</option>";
- }
- }
- } else {
- header('location: ./');
- }
- ?>
The above code is a simple PHP code which returns the list of states based on the country id from the database. mysqli_real_escape_string() function escapes special characters from a string. It is very useful to prevent SQL injection.
Complete Source Code – Populate a dropdown list based on selection of another dropdown list using ajax
Try the live demo example on Populate a dropdown list based on selection of another dropdown list using ajax. Download the complete source code from the below download link and please like and share the tutorial link with others.
0 comments:
Post a Comment