Dynamic and Dependent Select Box with jQuery, Ajax and PHP
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!
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
Excellent blog on Web technology!!! Have gained more information related to website development. Thank admin for this wonderful content.
ReplyDeletewebsite design training
website design courses
Again thank you for your feedback!
DeleteThank you for your feedback Anoushka Sakthi.. Your words encouraged me!
ReplyDeleteYou made some good points there. I did a search on the topic and found most people will agree with your blog
ReplyDeleteAlso Visit this site for to learn more about jQuery
Thanx Kimberly.. I'm pleasure to hear such a feedback..
DeleteIncredible blog on Web innovation. Have expanded more information related to web page headway. Thank manager for this wonderful substance.
ReplyDeleteArticle Submission sites | Latest Updates | Technology
Thank You BlackKutty! It's my pleasure..
DeleteNice blog. Really helpful for learning and keep update on some more tutorials….. I liked your blog.
ReplyDeleteArticles submission sites
Technology updates
Than you Malar!
DeleteWonderful post!!Thank you for sharing this info with us.
ReplyDeleteKeep 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
Thank You Vicky! I will publish the things as soon I experience them..
DeleteThank You for your great feedback! Sorry for late reply!
ReplyDeleteThanx Annie.. Nice to hear such comments!
ReplyDeleteYou are welcome Vicky! Keep in touch with TechPool!
ReplyDeleteThank you Xplore IT Corp! I won't stop blogging.. :D
ReplyDeleteHey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
ReplyDeletedigital marketing course in coimbatore
php training in coimbatore
Thank You ProPlus Academy!
DeleteThank You ProPlus Logics!
ReplyDeleteThanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information.
ReplyDeleteJava Training in Chennai
Java course in Chennai
Software Testing Training in Chennai
Web Designing Course in chennai
PHP Training in Chennai
Java Training in Tambaram
Java Training in OMR
Thanx pavithra..Keep in touch with TechPool!
DeleteNever seen article like this, thanks for the wonderful content.
ReplyDeleteGerman Classes in Chennai
Big Data Training in Chennai
Android Training in Chennai
Selenium Training in Chennai
JAVA Training in Chennai
Digital Marketing Training in Chennai
Salesforce Training in Chennai
Salesforce Training in Velachery
Thanx Anoushka..Keep in touch with TechPool!
DeleteGreat post! This is very useful for me and gain more information, Thanks for sharing with us.
ReplyDeleteArticle submission sites
Guest posting sites
You are welcome Vicky..Keep in touch with TechPool!
DeleteThanks for sharing your views about the concept which you know much better. Its easy to read and understand by the way you wrote the blog contents.
ReplyDeleteEthical hacking course in chennai
PHP Training in Chennai
PHP Course in Chennai
Hacking course in chennai
Hacking classes in chennai
PHP Training in Velachery
PHP Training in Tambaram
PHP Training in T nagar
Happy to hear..Thanx for your encouragement Karthik! Keep in touch with TechPool!
DeleteThanx Creators Seo Master..Keep in touch with TechPool!
ReplyDeleteThanx Gitani! Keep in touch with TechPool!
ReplyDeletePleasure to see your comments..Thanx shaivani for your encouragement Karthik! Keep in touch with TechPool!
ReplyDeleteThis will being a great blog. Everyone can read this blog to enhance your skills.
ReplyDeleteweb designing and development course training institute in Chennai with placement
PHP MySQL programming developer course training institute in chennai with placement
Magento 2 Developer course training institute in chennai
Thank you Christoper!
DeleteThis 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
ReplyDeleteThank you for your feedback Sophie! I will write more :D Keep in touch!
Delete"Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!
ReplyDeleteDigital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
"
Thank you very much saran :D
DeleteAfter after the above troubleshooting steps, you can actually fix printer problem in QuickBooks Support Phone Number good work
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
thanks saran :D
ReplyDeleteThere 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.
ReplyDeletehire python developers in US
Thank you very much for the feedback :D
DeleteThis comment has been removed by the author.
ReplyDeleteThanks a lot
Delete