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!
Dynamic and Dependent Select Box with jQuery, Ajax and PHP
Reviewed by DAL
on
January 03, 2018
Rating:
No comments: