PHP - Simple Dynamic Dependent Select Box Using jQuery

In this tutorial we will try to create a Simple Dynamic Dependent Select Box Using jQuery. jQuery is a cross-platform javaScript library design to simplified the modern HTML client side scripting. jQuery syntax was made to make it easier to navigate a document, like select DOM elements, develop Ajax applications and etc. So let's start coding...

Before we started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the jquery that i used in this tutorial https://jquery.com/. Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_food, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2.         $conn = new mysqli('localhost', 'root', '', 'db_food');
  3.        
  4.         if(!$conn){
  5.                 die("Error: Can't connect to database!");
  6.         }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.         <head>
  4.                 <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5.                 <link rel="stylesheet" tyoe="text/css" href="css/bootstrap.css"/>
  6.         </head>
  7. <body>
  8.         <nav class="navbar navbar-default">
  9.                 <div class="container-fluid">
  10.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class="col-md-3"></div>
  14.         <div class="col-md-6 well">
  15.                 <h3 class="text-primary">PHP - Simple Dynamic Dependent Select Box</h3>
  16.                 <hr style="border-top:1px dotted #ccc;"/>
  17.                 <button class="btn btn-primary" data-toggle="modal" data-target="#form_modal">Add Data</button>
  18.                 <br /><br />
  19.                 <div class  =  "form-inline">
  20.                         <label>Food Category:</label>
  21.                         <select id = "category" class = "form-control" required = "required">
  22.                                 <option value = "">Select a Category</option>
  23.                                         <?php
  24.                                                 require 'conn.php';
  25.                                                
  26.                                                 $query = $conn->query("SELECT * FROM `food` GROUP BY `food_category`");
  27.                                                 while($fetch = $query->fetch_array()){ 
  28.                                                
  29.                                         ?>
  30.                                         <option value="<?php echo $fetch['food_category']?>"><?php echo $fetch['food_category']?></option>
  31.                                         <?php
  32.                                                 }
  33.                                         ?>
  34.                         </select>
  35.                         <label>Food:</label>
  36.                         <select  id = "food" class = "form-control" disabled = "disabled" required = "required">
  37.                                 <option value = "">Select a food</option>
  38.                         </select>
  39.                 </div> 
  40.         </div>
  41.         <div class="modal fade" id="form_modal" tabindex="-1" role="dialog" aria-hidden="true">
  42.                 <div class="modal-dialog" role="document">
  43.                         <form action="save_query.php" method="POST">
  44.                                 <div class="modal-content">
  45.                                         <div class="modal-body">
  46.                                                 <div class="col-md-2"></div>
  47.                                                 <div class="col-md-8">
  48.                                                         <div class="form-group">
  49.                                                                 <label>Food Category</label>
  50.                                                                 <input class="form-control" type="text" name="food_category">
  51.                                                         </div>
  52.                                                         <div class="form-group">
  53.                                                                 <label>Food</label>
  54.                                                                 <input class="form-control" type="text" name="food" />
  55.                                                         </div>
  56.                                                         <div class="form-group">
  57.                                                                 <button class="btn btn-primary form-control" name="save"><span class="glyphicon glyphicon-save"></span> Save</button>
  58.                                                         </div>
  59.                                                 </div>
  60.                                         </div>
  61.                                         <div style="clear:both;"></div>
  62.                                         <div class="modal-footer">
  63.                                                 <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  64.                                                 <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
  65.                                         </div>
  66.                                 </div>
  67.                         </form>
  68.                 </div>
  69.         </div>
  70. </body>
  71. <script src="js/jquery-3.2.1.min.js"></script>
  72. <script src="js/bootstrap.js"></script>
  73. <script src="js/script.js"></script>
  74. </html>

Creating PHP Queries

This code contains the php query of the application. This code can store your data inputs to the database server, and then will return a data from the database to html jQuery request method. To do that just copy and write this block of codes inside the text editor, then save it as shown below. save_query.php
  1. <?php
  2.         require_once 'conn.php';
  3.        
  4.         if(ISSET($_POST['save'])){
  5.                 if(!empty($_POST['food_category']) && !empty($_POST['food'])){
  6.                         $food_category = addslashes($_POST['food_category']);
  7.                         $food = addslashes($_POST['food']);
  8.                        
  9.                        
  10.                         $conn->query("INSERT INTO `food` VALUES('', '$food_category', '$food')");
  11.                         echo "<script>alert('Data Inserted!')</script>";
  12.                         echo "<script>window.location = 'index.php'</script>";
  13.                 }else{
  14.                         echo "<script>alert('Please complete the required field!')</script>";
  15.                         echo "<script>window.location = 'index.php'</script>";
  16.                 }
  17.         }
  18. ?>
food_get.php
  1. <?php
  2.         require_once 'conn.php';
  3.        
  4.         $query = $conn->query("SELECT * FROM `food` WHERE `food_category` = '$_REQUEST[food_category]'") or die(mysqli_error());
  5.         echo '<option value = "">Select a food</option>';
  6.        
  7.         while($fetch = $query->fetch_array()){
  8.                         echo '<option value = "'.$fetch['food'].'">'.$fetch['food'].'</option>';
  9.         }
  10. ?>

Creating The jQuery Script

This is where the code that uses jquery script been used. This code will retrieve the target data from the database to be display in the select option. To do this just copy and write these block of codes inside the text editor, then save it as script.js inside the js folder.
  1. $(document).ready(function(){
  2.         $('#category').on('change', function(){
  3.                 if($('#category').val() == ""){
  4.                         $('#food').empty();
  5.                         $('<option value = "">Select a food</option>').appendTo('#food');
  6.                         $('#food').attr('disabled', 'disabled');
  7.                 }else{
  8.                         $('#food').removeAttr('disabled', 'disabled');
  9.                         $('#food').load('food_get.php?food_category=' + $('#category').val());
  10.                 }
  11.         });
  12. });
There you have it we successfully created a Simple Dynamic Dependent Select Box Using jQuery. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Comments

Very good tutorial, thank you for sharing. Have you ever thought of doing these small snippets in both mySQL and SQLite? Maybe give both examples in download? There are so many times that mySQL is an overkill and using SQLite is simple:) Just a thought and really enjoy your shares. Susan

Add new comment