dropdown list in php

How to make dependent dropdown list in php using jquery Ajax with demo

by Code4berry. Last modified on April 1st, 2022.

A dependent dropdown list in php is the best arrangement to get the client input in successive request. The Dependent dropdown is a valuable component when the dropdowns information are between related.

Dropdown list in php

The nation state interdependency is a traditional model situation for telling about the need of a ward dropdown. We can expand the length of the reliance stepping stool to 3, 4, etc.

When I got an opportunity to carry out this for in excess of 8 ward dropdowns. I did this for a hunt channel in material administration programming. In the event that you carry out this once for a couple of ward dropdown, the idea is something similar to do it for an extended grouping.

We can say many examples of such dependent entities, Categories-Sub-categories-Products in a shopping cart application, Department-Courses and more.

Below screenshot shows the dynamic dependent data fetch is in progress. The loader displayed in the dependent countries dropdown indicates it.

How to make dependent dropdown list using jquery Ajax

Once the endpoint got the data, then the script will return HTML response with dependent data. Then, the AJAX achievement callback will stack the reaction into the objective.In the following screenshot, we can see the state results based on the selected country.

How to make dependent dropdown list using jquery Ajax

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 "dropdown" database in your phpmyadmin. After created database successfully we require to create two new table "continents" and "countries" using following below SQL Query.

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 countries drop-down. In this file layout will display so put below code on index.php file.

index.php

								
									<?php
									require_once("config.php");
									?>
									<!DOCTYPE html>
									<html lang="en">
									<head>
									  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
									  <meta charset="utf-8">
									  <title>Dependant dropdown</title>
									  <meta name="generator" content="Bootply" />
									  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
									  <link href="css/bootstrap.css" rel="stylesheet">
									  <script>
									    function getSubcat(val) {
									      $.ajax({
									        type: "POST",
									        url: "get_subcat.php",
									        data:'cat_id='+val,
									        success: function(data){
									          $("#subcategory").html(data);
									        }
									      });
									    }
									    function selectCountry(val) {
									      $("#search-box").val(val);
									      $("#suggesstion-box").hide();
									    }
									  </script>
									</head>
									<body>
									  <div class="container">
									    <div> </div>
									    <p>Dependant dropdown using Ajax</p>
									    <div class="card col-md-8">
									      <div class=" col-md-8">
									        <<label class="">Continent </label>
									        <div class="">
									          <select name="faculty"  onChange="getSubcat(this.value);"  style="width: 100%; padding: 0.375rem 0.75rem;    border-color: #ced4da;">
									            <option value="">Select Continent</option>
									            <?php $query=mysqli_query($con,"select * from continent");
									            while($row=mysqli_fetch_array($query))
									            { 
									              ?>

									              <option value="<?php echo $row['id'];?>"><?php echo $row['ContinentName'];?></option>
									              <?php 
									            } ?>
									          </select>
									        </div>
									      </div>
									      <div class="control-group col-md-8">
									        <label class="control-label" for="basicinput">Country</label>
									        <div class="controls">
									          <select  style="width: 100%; padding: 0.375rem 0.75rem;    border-color: #ced4da;"   name="course"  id="subcategory">
									            <option value="">Select</option>
									          </select>
									        </div>
									      </div>
									      <div> </div>
									    </div>
									  </div>
									  
									  <script src="js/jquery.min.js"></script>
									  <script src="js/bootstrap.min.js"></script>
									</body>
									</html>
								
							

Step 3: Add Database Configuration File

Now we require to create database configuration file for database, that way you can set username, password, database and host. So let's create config.php file and put below code:

config.php

								
									<?php
									define('DB_SERVER','localhost');
									define('DB_USER','root');
									define('DB_PASS' ,'');
									define('DB_NAME', 'dropdown');
									$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
									// Check connection
									if (mysqli_connect_error())
									{
										echo "Failed to connect to MySQL: " . mysqli_connect_error();
									}
									?>
								
							

Step 4: Add Ajax File

In last step, we need to create ajax dropdown file, in this file we write code for dynamic ajax countries drop-down json data. So let's create get_subcat.php file and put below code:

get_subcat.php

								
									<?php
									include('config.php');
									if(!empty($_POST["cat_id"])) 
									{
										$id=intval($_POST['cat_id']);
										$query=mysqli_query($con,"SELECT * FROM countries WHERE continent_id=$id");
										?>
										<option value="">Select Country</option>
										<?php
										while($row=mysqli_fetch_array($query))
										{
											?>
											<option value="<?php echo htmlentities($row['id']); ?>"><?php echo htmlentities($row['country']); ?></option>
											<?php
										}
									}
									?>			
								
							
Download

Comments

Natasha Kara

This is the code that I was looking for many past years, thank you.

Gerald Bills

Thank you for this beautiful code

Perry Kat

I like what am seeing, thank you very much.

lasixDew

I’m not sure where you’re getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for wonderful info I was looking for this info for my mission.

antibioticsor

I needs to spend some time learning more or understanding more.

prednisoneor

Thanks for excellent information I was looking for this information for my mission.

Leave a Comment:

You Might Also Like

hostel booking

Hostel booking management system
Learn More
.

car rental

Car rental management system in Php
Learn More
.

student details

Student details management system
Learn More
.

Tourism

Tourism management system in Php and Mysql
Learn More

Latest Tutorial

sweet alerts

How to delete table row using sweet alert2
Learn More

piechart

How to create piechart with Mysql data
Learn More

register and login

How to register and login in php
Learn More

edit data

How to edit Mysql data in modal using php
Learn More