jQueryAjax Autoload Dropdown using PHP

 Creating Order form with jQuery Ajax Autoload Dropdowns using PHP, MySQL

 

Using jQuery AJAX, we can easily implement autoloading data in dropdown. Today, I will explain to you how to create autoloading dropdowns. I am giving a sample application.

When the application loaded, the jQuery ajax() method sends a request to the server file, and  loads the response data(locations) in the dropdown box. When the user changes the location value,  the second dropdown loads restaurants of that location. And if the user selects a restaurant, then the third dropdown filled with the products available in that restaurant. After the product chosen, price printed in the price box.
 
 
coding-zon-autoload-dropdown

Table of  contents




Here I created a sample order form

 

Step-1: Shows the complete  Files in a Folder, that are needed for this tutorial.

 So first create a project folder in the server and create files as shown in the image

 File Structure

 

 

e-trainings-ajax-dropdown-file-structure

 

Step-2: Creating Tables in MySQL Database

Create database and run the queries given below

 MoveUP

SQL Queries

--
-- Database: `ajaxdropdown`
--

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

--
-- Table structure for table `location`
--

CREATE TABLE IF NOT EXISTS `location` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `location` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

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

--
-- Table structure for table `products`
--

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `productName` varchar(255) NOT NULL,
  `price` varchar(255) NOT NULL,
  `restaurentId` bigint(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `productName`, `price`, `restaurentId`) VALUES
(1, 'Product-one', '150', 1),
(2, 'Product-two', '250', 1),
(3, 'Product-three', '300', 2),
(4, 'Product-four', '200', 2),
(5, 'Product-five', '150', 3),
(6, 'Product-six', '170', 3),
(7, 'Product-seven', '50', 4),
(8, 'Product-eight', '45', 4),
(9, 'Product-nine', '35', 5);

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

--
-- Table structure for table `restaurents`
--

CREATE TABLE IF NOT EXISTS `restaurents` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `restaurentName` varchar(255) NOT NULL,
  `locationId` int(11) NOT NULL,
  `restaurentStatus` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `locationId` (`locationId`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

 

Step-3: Creating Database Configuration  File.

Copy the following code in config.php 

 config.php

 <?php

define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'ajaxdropdown');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

?>
 
 


 MenuTOP

 
 
 
 

 HTML and BootStrap

 

Step-4: Creating Front end Page.

Copy the following code in index.php. It has  a form with 3 dropdowns, date, time widgets, price box and one submit button.


Order Form fields:

  1. Dropdown Locations:  When page is loaded locations are loaded.
  2. Dropdown  Restaurants: Loads the restaurants on change of Location in locations    dropdown
  3. Dropdown Products : Loads the products on change of restaurant in restaurants dropdown
  4. Price box : Displays price of the chosen product.
  5. Date : User selects order date
  6. Time : User chooses order time
  7. Submit Button

 

 index.php

 
 
<?php
include('config.php'); 
session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>e-Trainings Demo | Ajax Autoload DropDown Example</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="ajax.js"></script>
</head>

<body>
  
	<div class="container">
 
	<div class="row margin-top-30">
	<div class="col-lg-8 col-md-8">
	<h1 class="mainTitle">User | Place Order</h1>
		
	<h5><p style="color:green;"><?php echo htmlentities($_SESSION['msg']);?>
	<?php echo htmlentities($_SESSION['msg']="");?></p>	</h5>
 
 
	<form role="form" name="orderform" method="post" action="orders.php" >

	
	<div class="form-group">
	<label for="LocationId">Locations</label>
	<select name="location" id="LocationId" class="form-control" onChange="getRestaurents(this.value);">
	<option value="">Select Location</option>
	</select>
	</div>
	
	<div class="form-group">
	<label for="RestaurentId">Restaurents</label>
	<select name="restaurentId" id="restaurentId" class="form-control" onChange="getProducts(this.value);">
	 <option value="">Select Restaurent</option>  	
	</select>
	</div>

	<div class="form-group">
	<label for="ProductId">	Products</label>
	<select name="productId" id="productId" class="form-control"  onChange="getPrice(this.value);">
	<option value="">Select Product</option>
	</select>
	</div>
	
	
	<div class="form-group">
	<label for="price">	Price</label>
	<select name="price" id="price" class="form-control" readonly>
	</select>
	</div>
	
	<div class="form-group">
	<label for="OrderDate">Date</label>
	<input class="form-control datepicker" name="orderDate" type="date" required="required" data-date-format="yyyy-mm-dd">	
	</div>
	
	<div class="form-group">
	<label for="Ordertime">Time</label>
	<input class="form-control" name="orderTime" id="timepicker1" type="time" required="required">eg : 10:00 PM
	</div>														
	
	<button type="submit" name="submit" class="btn btn-o btn-primary">Submit</button>
	</form>
 
 
</div>

</div>
</div>
 
 
<!--  MAIN JAVASCRIPTS --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>
</html>
 


 GoToP

 

 JQuery Ajax

 
 

Step-5:Create jQuery Script File

Copy the following code in ajax.js

 

 ajax.js

 
 
 <!-------  Loding Locations ------------->

$( document ).ready(function() {
	
	$.ajax({
		type: "POST",
		url: "get_locations.php",
		data:'',
		success: function(data){
			$("#LocationId").html(data);
		}
	});
});

<!-------  Loding Restaurents ------------->


function getRestaurents(val) {
	$.ajax({
		type: "POST",
		url: "get_restaurents.php",
		data:'locationId='+val,
		success: function(data1){
			$("#restaurentId").html(data1);
		}
	});
}

<!-------  Loding Products ------------->


function getProducts(val) {
	
	$.ajax({
		type: "POST",
		url: "get_products.php",
		data:'restaurentId='+val,
		success: function(data){
			$("#productId").html(data);
		}
	});
}

<!-------  Loding Price ------------->

function getPrice(val) {
	$.ajax({
		type: "POST",
		url: "get_products.php",
		data:'productId='+val,
		success: function(data){
			$("#price").html(data)
			
		}
	});
}
 
 
 


 Move to ToP

 

 PHP Scripts

 

Step-6:Creating PHP Script Pages


Copy the following code  snippets in each PHP file as shown. And Run the index.php on the server
 

 

get_locations.php

 
<?php
 
include('config.php');

$sql = "SELECT * from location";
 
$res=mysqli_query($con,$sql);
 
while($row=mysqli_fetch_array($res))
{
?> 
 
<option value="<?php echo htmlentities($row['id']); ?>"><?php echo htmlentities($row['location']); ?></option>
 
<?php
}
?>
 
 


 MoveTOP

 

get_restaurents.php

 
<?php
include('config.php');
if(!empty($_POST["locationId"])) 
{

$sql2 =  "select id,restaurentName from restaurents where locationId= ".$_POST['locationId'];

$res = mysqli_query($con,$sql2);

$n = mysqli_num_rows($res);
if($n == 0)
{
?>
<option selected>No Restaurents </option>
<?php 
	}  else {
?>
<option selected>Select Restaurents </option>
<?php
}
while($row=mysqli_fetch_array($res))
{?>
<option value="<?php echo htmlentities($row['id']); ?>"><?php echo htmlentities($row['restaurentName']); ?></option>
<?php
}
}

?> 

 

get_products.php

 
 
<?php
include('config.php');
$n=0;

if(!empty($_POST["restaurentId"])) 
{

$sql= "SELECT id, productName from products WHERE restaurentId='".$_POST['restaurentId']."'";
$res = mysqli_query($con,$sql); 
$n = mysqli_num_rows($res);
if($n == 0)
{
?>
<option selected>No Products </option>
<?php 
}  else {
?>
<option selected>Select Product </option>
<?php
}

while($row=mysqli_fetch_array($res))
{?>
<option value="<?php echo htmlentities($row['id']); ?>"><?php echo htmlentities($row['productName']); ?></option>
<?php
}
}


if(!empty($_POST["productId"])) 
{

$sql2 =  "SELECT price from products WHERE id= '".$_POST['productId']."'";


$res = mysqli_query($con,$sql2);
while($row=mysqli_fetch_array($res))
{?>
<option value="<?php echo htmlentities($row['price']); ?>"><?php echo htmlentities($row['price']); ?></option>
<?php
}
}

?>
 
 


 Menu

 

orders.php


 <?php
session_start();
include('config.php');

if(isset($_POST['submit']))
{
	$locationId=$_POST['location']; 
	$restaurentId=$_POST['restaurentId'];
	$productid=$_POST['productId'];
	$price=$_POST['price'];
	$orderDate=$_POST['orderDate'];
	$orderTime=$_POST['orderTime'];
	
	$_SESSION['msg'] = "Order Success";
	header("Location:index.php");
	
?>
 
 

 

Source code:

Download
 
 
 
 
 

View Demo:






 

 

 

Go by Tags: 

Populate multiple dropdown lists using Ajax, jQuery.

Dynamic Dependent Select Box using jQuery, Ajax and PHP, MySQL.

Auto Load Second Dropdown using AJAX .

 

 


Comments

Popular posts from this blog

Recently viewed list in PHP Mysql

Import CSV File Into MySQL Using PHP

Shoppingcart using PHP Sessions - Miniproject