Hi guys! Today I'm going to explain you another jQuery tutorial. It's a very interesting one. Imagine that you want want to search a province of a country. Currently you have a list of countries and a list of provinces. List of provinces will be quite longer one since there are so many provinces per each country. If all those provinces are mixed together in one list, it's hard to find the needed record. Isn't it? If the list of provinces is shown filtered according to the country, I think it will be better. That means first you select the country. Then the provinces are listed which belongs to that selected country only! You got it? This is the application that I'm going to create today..Let's start!

This is a short demo of the application that we are going to create now! 



Download source code : Dynamic Select Box

First we need to create the project folder. Give a name a you want. Then you will need 3 PHP files. One for database connection, another one to fetch data and the other is for displaying the view. 

index.php     =>    main view and scripts
dbcon.php    =>    build DB connection
fetch_model.php      =>    retrieve data from database

We need to create a database first. Go to phpmyadmin and create a new database called products. Then import the SQL file I have included in my GitHub project. You can create your own one which have two tables and they should be dependent on each other. Simply, primary key of one table should be the foreign key of the other table. Here I have selected mobile phone brands and models

Ok...Now create the dbcon.php file and code in it to build up the database connection for the project. Each code of the files are explained using comments. So, here I will explain only the additional things. 

dbcon.php


<?php
//build the connection variable and assign database credentials
$conn = mysqli_connect('localhost','root','','products');

//if DB connection fails, get a error message
if(!$conn){
    die('Connection Failed'.mysqli_connect_error());
}
?>

Then we can move to code index.php file which provides the main view for our project. 
We include our jQuery and Ajax scripts also in this file. First I will give you the code without that scripts.

<!DOCTYPE html>
<head>
 <title>Search Products</title>
 <meta charset="UTF-8">
 <!-- Bootstrap CSS styles -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 <!-- Google jQuery CDN -->
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <!-- Roboto Google font -->
 <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
 <!-- Custom Styles -->
 <style type="text/css">
  body {
   padding-top: 50px;
   font-family: 'Roboto', sans-serif;
   font-size: 16px;
  }
  h1 {
   margin-bottom: 60px;
  }
 </style>
</head>
<body>
<?php
function get_brand(){
 // Build up DB connection including cofiguration file
 require ("dbcon.php");
 //Assign an empty variable to store the fetched items
 $output = '';
 //SQL query to fetch the phone brands to the input field
 $sql = "SELECT * FROM brands ORDER BY brand_id";
 // execution of the query. Output a boolean value
 $res = mysqli_query($conn , $sql);
 // Check whether there are results or not
 if(mysqli_num_rows($res)>0){
  while ($row = mysqli_fetch_array($res)) {
   //Concatenate fetched items to the output variable with HTML option tags to display
   $output .= '<option value="'.$row["brand_id"].'">'.$row["brand_name"].'</option>';
  }
 }
 //return the output results to be displayed
 return $output;
}
?>
<div class="container">
 <div class="row">
  <center>
   <h1>Dynamic Select Box using jQuery, Ajax and PHP
   </h1>
  </center>
  <div class="col-lg-4"></div>
  <div class="col-lg-4">   
   <div class="form-group">
    <label for="brand">Mobile Phone Brand</label>
    <select name="brand" id="brand" class="form-control">
     <option value="">Select Phone Brand</option>
     <!-- load the PHP function to fetch the brand names -->
     <?php echo get_brand(); ?>
    </select> 
   </div>
   <br><br>
   <div class="form-group">
    <label for="item">Phone Model</label>
    <select name="item" id="item" class="form-control">
     <option value="">Select Phone Model</option>
    </select> 
   </div>   
  </div>
  <div class="col-lg-4"></div>
 </div>
</div> 
<!-- Bootstrap JS file -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>

Function get_brand is a PHP function wrote to fetch the brand names to the drop-down box in the view. But remember, here we get data only for drop-down reserved to select the mobile brands. Fetching data for the drop-down box reserved to display mobile phone models is done later using jQuery and Ajax.

Now we have come to the most important code section! That is our jQuery function guys! Let's move for it. Include the following code just before the ending body tag.

<!-- start jQuery function -->
<script type="text/javascript">
 // start jQuery function to load the content of all functions after the page is loaded completely
 $(document).ready(function(){
  //jQuery function to get the value changed in the input field
  $('#brand').change(function(){
   //Store the selected input value in brand_id variable
   var brand_id = $(this).val();
   // start Ajax call to get the models belongs to a particular brand_id
   $.ajax({
    url: "fetch_model.php",  //Path for PHP file to fetch phone models from DB
    method: "POST",    //Fetching method
    data: {brand_id:brand_id}, //Data send to the server to get the results
    success:function(data)  //If data fetched successfully from the server, execute this function
    {
     // console.log(data);
     $('#item').html(data); //Print the fetched models in the section wih ID - #item
    }
   });
   // end Ajax call to get the suggestions
  });
 });
</script> 
<!-- end jQuery function -->

Done and dusted guys! You will be getting the records as we thought...

Ok! Now we have reached the end of this article. I think you will gain some knowledge to work with jQuery and Ajax applications though this. I'm also still learning these interesting technologies. When I try a new thing I will definitely share my experience with you! Keep in touch with TechPool..
Bye guys!



41 Comments

  1. Excellent blog on Web technology!!! Have gained more information related to website development. Thank admin for this wonderful content.
    website design training
    website design courses

    ReplyDelete
  2. Thank you for your feedback Anoushka Sakthi.. Your words encouraged me!

    ReplyDelete
  3. You made some good points there. I did a search on the topic and found most people will agree with your blog

    Also Visit this site for to learn more about jQuery

    ReplyDelete
    Replies
    1. Thanx Kimberly.. I'm pleasure to hear such a feedback..

      Delete
  4. Incredible blog on Web innovation. Have expanded more information related to web page headway. Thank manager for this wonderful substance.
    Article Submission sites | Latest Updates | Technology

    ReplyDelete
  5. Nice blog. Really helpful for learning and keep update on some more tutorials….. I liked your blog.
    Articles submission sites
    Technology updates

    ReplyDelete
  6. Wonderful post!!Thank you for sharing this info with us.
    Keep updating I would like to know more updates on this topic
    Very useful content, I would like to suggest this blog to my friends.

    PHP Training Chennai

    PHP Training Center in Chennai

    ReplyDelete
    Replies
    1. Thank You Vicky! I will publish the things as soon I experience them..

      Delete
  7. Thank You for your great feedback! Sorry for late reply!

    ReplyDelete
  8. Thanx Annie.. Nice to hear such comments!

    ReplyDelete
  9. You are welcome Vicky! Keep in touch with TechPool!

    ReplyDelete
  10. Thank you Xplore IT Corp! I won't stop blogging.. :D

    ReplyDelete
  11. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    digital marketing course in coimbatore
    php training in coimbatore

    ReplyDelete
  12. Great post! This is very useful for me and gain more information, Thanks for sharing with us.

    Article submission sites
    Guest posting sites

    ReplyDelete
    Replies
    1. You are welcome Vicky..Keep in touch with TechPool!

      Delete
  13. Replies
    1. Happy to hear..Thanx for your encouragement Karthik! Keep in touch with TechPool!

      Delete
  14. Thanx Creators Seo Master..Keep in touch with TechPool!

    ReplyDelete
  15. Thanx Gitani! Keep in touch with TechPool!

    ReplyDelete
  16. Pleasure to see your comments..Thanx shaivani for your encouragement Karthik! Keep in touch with TechPool!

    ReplyDelete
  17. This blog is very informative for a lot of people. I hope you will soon share your next post about this discussion. Thank you for sharing great and cool information. Keep it up. PLease go to site instastalker to see more information

    ReplyDelete
    Replies
    1. Thank you for your feedback Sophie! I will write more :D Keep in touch!

      Delete
  18. There will be no easier way to explain this to us. In particular, thanks for sharing this valuable knowledge with us about jQuery, Ajax and PHP for using dynamic and dependent selection boxes.

    hire python developers in US

    ReplyDelete