Thursday, 26 April 2018

Multi Select Dynamic Dependent Select box using PHP Ajax



Hi, In this post we have implement multi select dynamic dropdown list box by using PHP with Ajax. Dynamic dependent select box means child select box data has been depend on value of parent select box. But this is single option dropdown list box and in which we can select only single option and based on selected option value it will load data in child load. But in web development we want to required to select multiple option from select box and based on that selected option we want to load data related to selected multiple option in child selectbox. For this we have make this tutorial.

For make multi select dynamic dependent select box using PHP with Ajax, we have use Bootstrap Multiselect plugin. This is a plugin for jQuery and Bootstrap which allows the user to select multiple options by checked on checkboxes. Here we will make multiple select dropdown listbox by using Bootstrap Multiselect plugin. Here we will make three different multi select dropdown listbox. So, when page has been load into browser then only first level select box has been filled with data and both child select box has been blank, so when we have select option from first selectbox option then selected of multiple option value, it will load data into second level category data which connected with value of first level category value with out refresh of web page. Same way when we have select multiple option from second level category option, then in third level category dropdown will be filled with data on the basis on selection of option from second level dropdown list. This way it this script will work.

Here we have use simple PHP script with Ajax and for make multiple selection dropdown listbox we have use Bootstrap Multiselect plugin. If you have know single selection dynamic dependent selectbox then you get better idea regarding this tutorial. In which we can select multiple option in parent select box and child dropdown listbox will be filled with data based on value of option selection in parent select box.








Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO('mysql:host=localhost;dbname=test', 'root', '');

?>


index.php



<?php

//index.php

include('database_connection.php');

$query = "
SELECT * FROM first_level_category 
ORDER BY first_level_category_name ASC
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Bootstrap Multi Select Dynamic Dependent Select box using PHP Ajax </title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">Multi Select Dynamic Dependent Select box using PHP Ajax</h2>
   <br /><br />
   <div style="width: 500px; margin:0 auto">
    <div class="form-group">
     <label>First Level Category</label><br />
     <select id="first_level" name="first_level[]" multiple class="form-control">
     <?php
     foreach($result as $row)
     {
      echo '<option value="'.$row["first_level_category_id"].'">'.$row["first_level_category_name"].'</option>';
     }
     ?>
     </select>
    </div>
    <div class="form-group">
     <label>Second Level Category</label><br />
     <select id="second_level" name="second_level[]" multiple class="form-control">

     </select>
    </div>
    <div class="form-group">
     <label>Third Level Category</label><br />
     <select id="third_level" name="third_level[]" multiple class="form-control">

     </select>
    </div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){

 $('#first_level').multiselect({
  nonSelectedText:'Select First Level Category',
  buttonWidth:'400px',
  onChange:function(option, checked){
   $('#second_level').html('');
   $('#second_level').multiselect('rebuild');
   $('#third_level').html('');
   $('#third_level').multiselect('rebuild');
   var selected = this.$select.val();
   if(selected.length > 0)
   {
    $.ajax({
     url:"fetch_second_level_category.php",
     method:"POST",
     data:{selected:selected},
     success:function(data)
     {
      $('#second_level').html(data);
      $('#second_level').multiselect('rebuild');
     }
    })
   }
  }
 });

 $('#second_level').multiselect({
  nonSelectedText: 'Select Second Level Category',
  buttonWidth:'400px',
  onChange:function(option, checked)
  {
   $('#third_level').html('');
   $('#third_level').multiselect('rebuild');
   var selected = this.$select.val();
   if(selected.length > 0)
   {
    $.ajax({
     url:"fetch_third_level_category.php",
     method:"POST",
     data:{selected:selected},
     success:function(data)
     {
      $('#third_level').html(data);
      $('#third_level').multiselect('rebuild');
     }
    });
   }
  }
 });

 $('#third_level').multiselect({
  nonSelectedText: 'Select Third Level Category',
  buttonWidth:'400px'
 });

});
</script>


fetch_second_level_category.php



<?php

//fetch_second_level_category.php

include('database_connection.php');

if(isset($_POST["selected"]))
{
 $id = join("','", $_POST["selected"]);
 $query = "
 SELECT * FROM second_level_category 
 WHERE first_level_category_id IN ('".$id."')
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["second_level_category_id"].'">'.$row["second_level_category_name"].'</option>';
 }
 echo $output;
}

?>


fetch_third_level_category.php



<?php

//fetch_third_level_category.php

include('database_connection.php');

if(isset($_POST["selected"]))
{
 $id = join("','", $_POST["selected"]);
 $query = "
 SELECT * FROM third_level_category 
 WHERE second_level_category_id IN ('".$id."')
 "; 
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["third_level_category_id"].'">'.$row["third_level_category_name"].'</option>';
 }
 echo $output;
}




?>


Database



--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `first_level_category`
--

CREATE TABLE `first_level_category` (
  `first_level_category_id` int(11) NOT NULL,
  `first_level_category_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `first_level_category`
--

INSERT INTO `first_level_category` (`first_level_category_id`, `first_level_category_name`) VALUES
(1, 'Electronics & Electrical'),
(2, 'Apparel & Garments'),
(3, 'Automobile Parts'),
(4, 'Construction Material');

-- --------------------------------------------------------

--
-- Table structure for table `second_level_category`
--

CREATE TABLE `second_level_category` (
  `second_level_category_id` int(11) NOT NULL,
  `first_level_category_id` int(11) NOT NULL,
  `second_level_category_name` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `second_level_category`
--

INSERT INTO `second_level_category` (`second_level_category_id`, `first_level_category_id`, `second_level_category_name`) VALUES
(1, 1, 'Audio Video Equipment'),
(2, 1, 'Water Heater'),
(3, 1, 'Air Conditioner'),
(4, 2, 'Children Clothing'),
(5, 2, 'Women Wear'),
(6, 2, 'Men Wear'),
(7, 3, 'Auto Parts'),
(8, 3, 'Auto Accessories'),
(9, 3, 'Auto Electronics'),
(10, 4, 'Tiles'),
(11, 4, 'Plywood'),
(12, 4, 'Sanitaryware');

-- --------------------------------------------------------

--
-- Table structure for table `third_level_category`
--

CREATE TABLE `third_level_category` (
  `third_level_category_id` int(11) NOT NULL,
  `second_level_category_id` int(11) NOT NULL,
  `third_level_category_name` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `third_level_category`
--

INSERT INTO `third_level_category` (`third_level_category_id`, `second_level_category_id`, `third_level_category_name`) VALUES
(1, 1, 'Mini FM Radio'),
(2, 1, 'LCD TV'),
(3, 1, 'Music Player'),
(4, 2, 'Solar Water Heater'),
(5, 2, 'Thermic Fluid Heater'),
(6, 2, 'Portable Water Heater'),
(7, 3, 'Portable Air Conditioner'),
(8, 3, 'Air Conditioner Part'),
(9, 3, 'Commercial Air Conditioner'),
(10, 4, 'Baby Clothes'),
(11, 4, 'Kids Garments'),
(12, 4, 'Designer Clothes'),
(13, 5, 'Legging'),
(14, 5, 'Ladies Fashion Garments'),
(15, 5, 'Gown Dresses'),
(16, 6, 'Men Formal Wear'),
(17, 6, 'Mens Kurtas'),
(18, 6, 'Mens Lower'),
(19, 7, 'Car Shock Absorber'),
(20, 7, 'Glass Cleaning Wiper'),
(21, 7, 'Steering Lock'),
(22, 8, 'Grille Light'),
(23, 8, 'Automobile Couplings'),
(24, 8, 'Motorcycle Helmet'),
(25, 9, 'Car Audio System'),
(26, 9, 'Car Lcd'),
(27, 9, 'Car Stereos'),
(28, 10, 'Stone Tiles'),
(29, 10, 'Zig Zag Tiles'),
(30, 10, 'Granite Tiles'),
(31, 11, 'Flexible Plywood'),
(32, 11, 'Designer Plywood'),
(33, 11, 'Commercial Plywood'),
(34, 12, 'Brass Sanitary Fittings'),
(35, 12, 'Porcelain Toilet'),
(36, 12, 'Lavatory Basin'),
(37, 12, 'Kitchen Sink');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `first_level_category`
--
ALTER TABLE `first_level_category`
  ADD PRIMARY KEY (`first_level_category_id`);

--
-- Indexes for table `second_level_category`
--
ALTER TABLE `second_level_category`
  ADD PRIMARY KEY (`second_level_category_id`);

--
-- Indexes for table `third_level_category`
--
ALTER TABLE `third_level_category`
  ADD PRIMARY KEY (`third_level_category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `first_level_category`
--
ALTER TABLE `first_level_category`
  MODIFY `first_level_category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `second_level_category`
--
ALTER TABLE `second_level_category`
  MODIFY `second_level_category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;

--
-- AUTO_INCREMENT for table `third_level_category`
--
ALTER TABLE `third_level_category`
  MODIFY `third_level_category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;

15 comments:

  1. Your dependent dropdown list is really helpful, found it on youtube!

    ReplyDelete
  2. do you make this version of codeigniter?

    ReplyDelete
  3. how to do this in edit time please tell me

    ReplyDelete
  4. Very useful tutorial. Can you tell me how can I restrict user from selecting more then 2 options? Thanks.

    ReplyDelete
  5. Nice and useful...I'm binding drop down but select multiple first levels and then select only one option of each first levels. Can you help me.

    ReplyDelete
  6. Nice and useful. I'm binding drop down with multiple select first level but i want only one option of second level related to each first level. Can you suggest me.

    ReplyDelete
  7. i have inserted into my database but i get the id values and not strings. pls help asap. thanks

    ReplyDelete
  8. help me you can teach by laravel.

    ReplyDelete
  9. help me!
    I hope you give exemple by laravel .

    ReplyDelete
  10. Do it same project with laravel..please

    ReplyDelete
  11. Dear code programmer,

    You gave me a help with indefinitive efficiency. Congratulations and thank you for your sharing.

    Best regards!!!

    ReplyDelete
  12. Very useful tutorial. Can you please create a similar multi select dynamic dependent example using json file having hierarchy like continent, country, state, city, address

    ReplyDelete
  13. Can you guys make the code with vanilla js or jquery? Much appreciate!

    ReplyDelete
  14. How to make this form pre filled based on earlier submission

    ReplyDelete