Creating a Dependent Dropdown List with PHP, jQuery and Ajax.

There are times in a web application where you want to populate a dropdown list based on the value of another drop down list. Scenarios like this can be populating a Country’s State dropdown based on the value of the Country selected, populating product sub-categories based on the parent category. In this example, we will be creating a dropdown list for category/subcategory for a product in an eCommerce website. Create a database called dependent_list. We will Create 2 tables: categories and subcategories with the following queries:
  1. CREATE TABLE IF NOT EXISTS `categories` (
  2. `id` INT(11) NOT NULL AUTO_INCREMENT,
  3. `category_name` VARCHAR(100) NOT NULL,
  4. PRIMARY KEY (`id`)
  5. ) ENGINE=InnoDB;
  6.  
  7. CREATE TABLE IF NOT EXISTS `subcategories` (
  8. `id` INT(11) NOT NULL AUTO_INCREMENT,
  9. `categoryID` INT(11) NOT NULL,
  10. `subcategory_name` VARCHAR(100) NOT NULL,
  11. PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB;
Some data has been inserted into both tables as shown in database. categoryID is a foreign key in subcategories table i.e 1 category has multiple subcategories. Create a project folder called ‘dependent_list’ in your site root folder. Create a config.php file to store the database connection and add the following code:
  1. <?php
  2.  
  3. mysql_connect('localhost', 'root', '');
  4. mysql_select_db('dependent_list');
  5.  
  6. ?>
Next Create an index.php file in the project folder and add the following code:
  1. <?php
  2. include('config.php');
  3. $query_parent = mysql_query("SELECT * FROM categories") or die("Query failed: ".mysql_error());
  4. ?>
  1. <!doctype html>
  2. <meta charset="utf-8">
  3. <title>Dependent DropDown List</title>
  4. <script type="text/javascript" src="js/jquery.js"></script>
  5. <script type="text/javascript">
  6. $(document).ready(function() {
  7.  
  8. $("#parent_cat").change(function() {
  9. $(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
  10. $.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
  11. $("#sub_cat").html(data);
  12. $('#loader').slideUp(200, function() {
  13. $(this).remove();
  14. });
  15. });
  16. });
  17.  
  18. });
  19. </head>
  20.  
  21. <form method="get">
  22. <label for="category">Parent Category</label>
  23. <select name="parent_cat" id="parent_cat">
  24. <?php while($row = mysql_fetch_array($query_parent)): ?>
  25. <option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
  26. <?php endwhile; ?>
  27. </select>
  28. <br/><br/>
  29.  
  30. <label>Sub Category</label>
  31. <select name="sub_cat" id="sub_cat"></select>
  32. </form>
  33. </body>
  34. </html>
On line 3, we queried our categories table to get all categories. We then populate the parent_cat dropdownlist with the categories on lines 33-37. Whenever the dropdown value for category is changed, a jquery changed event is triggered for the category dropdown list on line 10. On lines 10-18,it sends the id value of the selected category through jquery Ajax to a php script called loadsubcat.php which then queries the subcategories table for subcategories that belongs to the parent category id value using $_GET[] super global . The values returned is now appended to the sub_cat dropdown list. We also added an animated loading gif for user experience, it is displayed when the a value is selected for the parent category and removed using a jquery “slideUp” method after the subcategory has been populated. Lastly, create a loadsubcat.php file in the project folder and add the following code.
  1. <?php
  2. include('config.php');
  3.  
  4. $parent_cat = $_GET['parent_cat'];
  5.  
  6. $query = mysql_query("SELECT * FROM subcategories WHERE categoryID = {$parent_cat}");
  7. while($row = mysql_fetch_array($query)) {
  8. echo "<option value='$row[id]'>$row[subcategory_name]</option>";
  9. }
  10.  
  11. ?>
Now go to http://localhost/dependent_list and you will see how the dependent dropdownlist works

Comments

Submitted byMurulimadhav (not verified)on Tue, 09/17/2013 - 12:31

Respected Sir, This is really nice scirpt, which is very essential in php to get records based on category. Murulimadhav
Submitted byAstroShiksha (not verified)on Wed, 09/18/2013 - 23:47

Respected Sir, I have around 7 dependent dropdowns on one by one, and is it possilbe to use this script to get sub categories in multiple dropdowns ? or for each two we have to rewrite the same script ? I hope you will guide me with the necessary directions. AstroShiksha
Submitted byAnonymous (not verified)on Tue, 09/24/2013 - 00:26

Very clean and good example. I was using something similar but my form was not "post"ing dynamically generated fields with ajax to next page. Applied your method and it works like a charm now :) thanks for this.
Submitted byilavenilon Wed, 10/16/2013 - 23:12

Hi kabiru, I have posted a question related to your article in http://stackoverflow.com/questions/19405321/create-two-dependent-dropdown-list Can you pls look at the code and let me know where i had made the mistake....Please help!!!

I copied this code and done everything as explained but the subcategory list is not being populated only the categories. Did this code work properly for others? not sure why its not working for me..
Submitted byJustin (not verified)on Thu, 01/09/2014 - 13:05

thanks for the tutorial i had to modify some codes in the loadsubcat.php file.
Submitted bysquare_eyes1234 (not verified)on Fri, 03/14/2014 - 22:05

Thanks for this:) It really simplified dynamic, dependent lists for me.
Submitted bymary walter (not verified)on Thu, 04/10/2014 - 18:41

I am able to retrieve the data,it works well..but how am I suppose to do if I want to insert both of the selected data to the database because the form use GET method, as we know that we must use POST as the form method to insert the data to the database..??anyone please help me... !!

Submitted bygeorge1978 (not verified)on Fri, 04/11/2014 - 08:40

Hi, i checked out this script,Creating a Dependent Dropdown List with PHP, jQuery and Ajax., and found it really nice and suitable for my needs . the only problem is that for my case i need two or maybe three more drop downs to be added to the script, linked and dependent from each other.so, when the last drop down of the script ends, meaining the sucategories, i want another one linked to subcategories and another one(dropdownlist3) linked to the previous, and another one last, (drop-downlist4) leading to the previous one(drop-downlist4). I hope you can help me cause i cannot figure the way out, and this script is really suitable if the dropdowns i need are added. Thanks in advance. george.
Submitted byanmol (not verified)on Wed, 04/16/2014 - 17:58

nice ...this is what i want.....!!
Submitted byGiorgi (not verified)on Fri, 04/18/2014 - 20:53

I make 3 categories ;)
Submitted byDss (not verified)on Wed, 06/18/2014 - 03:39

In reply to by Giorgi (not verified)

Can you show how you made 3? Did you just make a new "subsubcategories" table or did you reuse the same "subcategories" table by adding a new parent hierarchy?
Submitted bynur (not verified)on Fri, 06/13/2014 - 15:07

hye tqsm for benefiting me and lots of ppl.....u r d best
Submitted byyogeswar (not verified)on Fri, 06/27/2014 - 12:36

Sir, The code what u provided was working good for two dropdowns ,if i want to make 5(five)dropdowns dependent on each other ,what should i do
Submitted byRon Mullis (not verified)on Mon, 07/21/2014 - 11:51

I've been able to link the second dropdown to the 1st, but how do you "post" the values selected once they are selected?
Submitted bymelancholy (not verified)on Mon, 01/05/2015 - 13:39

I need to make 3 dependent drop downs... second drop down is dependent on the first and 3rd drop down is dependent on the second using codeigniter. I badly need help :(
Submitted byNUR FADZLIANA (not verified)on Tue, 12/22/2015 - 10:53

Love this codes ! Thanks a lot kabiru10. To much help :)
Submitted byDeny Wirat Raur (not verified)on Fri, 08/06/2021 - 07:09

I wanna take data from
"dependent dropdown list
and insert to another table. How to to execute it?? Thank for this helpfull tutorial.

Add new comment