Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks

Show dropdown list from ajax response in jQuery

Aman Jain, September 10, 2021September 10, 2021

Showing Dynamic Select Box using jQuery and Php,MySql

In this tutorial, we are going to learn the dropdown list using AJAX. Loading dropdown values from AJAX requires knowledge of javascript, jQuery, php and html.

Sometimes it requires to load the dropdown like countries, state, city list dependently. In this case jQuery AJAX come in to the role to load the list.

Follow the below steps to create dynamic select box list with php.

Step 1: Create a html file

In the first step, we are going to create a simple html file which contain the html and jQuery for populate the dynamic select box through jQuery and php web request.

<!DOCTYPE html>
<html>
<body>

<h2>Dynamic select box - Readerstacks.com</h2>

<form action="/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br><br>

  <label for="fname">Country:</label><br>
  <select type="text" id="country" name="country">
  
</select>	  
  <br><br>

  <label for="fname">State:</label><br>
  <select type="text" id="state" name="state">
  </select>	  

  <br><br>
  
  <input type="submit" value="Submit">
</form>
<!-- jQuery Library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<!-- jQuery Library -->

<!-- start of dynmic select box script -->
<script>
$(function(){

	$.post("load-dropdown.php",{country_id:$(this).val(),action:"load-country"},function(data){
			$("#country").html(data);
		});

	$(document).on("change","#country",function(){
		$.post("load-dropdown.php",{country_id:$(this).val(),action:"load-state"},function(data){
			$("#state").html(data);
		});
	})
});
</script>
<!-- end of dynmic select box script -->
</body>
</html>

In the above code, i have created a form with 2 select box one is for country and another one is for state. On change of country i am loading the relative state from php and mysql. I also added jQuery cdn library and then load the country list on load.

Step 2 : Create php file and load dynamic data

Now, we will create a php file in same folder and create the connection with mysql database to load the country state data.

load-dropdwn.php

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dynamic_dropdown";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
// echo "Connected successfully";


//check which action response accordingly

if($_POST["action"]=="load-country"){    
	echo loadCountry();
}
else if($_POST["action"]=="load-state"){
	echo loadState($_POST["country_id"]);
}

//load country and return country list
function loadCountry(){
	global $conn;
	$sql = "SELECT id, name FROM countries";
	$result = $conn->query($sql);
	$options='<option>select country</option>';
	if ($result->num_rows > 0) {
	  // output data of each row
	  
	  while($row = $result->fetch_object()) {
		$options.= "<option value='$row->id'>$row->name</option>";
	  }
	} 
	return $options;
}

//load state and return state list 
function loadState($country_id){
	global $conn;
	$sql = "SELECT id, name FROM states where country_id='$country_id'";
	$result = $conn->query($sql);
	$options='<option>select state</option>';
	if ($result->num_rows > 0) {
	  // output data of each row
	  
	  while($row = $result->fetch_object()) {
		$options.= "<option value='$row->id'>$row->name</option>";
	  }
	}  
	return $options;
}


$conn->close();
?>

Here, we initialised the database connection then loading the dropdown according to the POST params.

Screesshots:

  • Screenshot 2021 09 10 at 7.44.25 AM
  • Screenshot 2021 09 10 at 7.44.35 AM
  • Screenshot 2021 09 10 at 7.44.51 AM

Code Repo:

Download Code

Related

Javascript Php

Post navigation

Previous post
Next post

Related Posts

Javascript Angular Focusout Event on Input Example

Angular Focusout Event on Input Example

September 24, 2022March 16, 2024

Angular Focusout Event on Input is an Angular event binding it triggers when user interacts with DOM like text based input element and focus get out from the element. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular FocusOut…

Read More
Php How to Implement JWT Auth in Laravel

How to Implement JWT Auth in Laravel 9 ?

May 31, 2022August 20, 2022

JWT (Json Web Token) is used to create the authentication between two parties client and server that means it creates a secure information transactions between two parties. In the process of php-open-source-saver/jwt-auth token it creates a token claims and generates a token behalf of these claims then it verify on…

Read More
Php Ajax Image Upload with form in Laravel 8 9 with example

Ajax Image Upload with form in Laravel 8 / 9 with example

June 3, 2022June 4, 2022

Ajax image Upload with preview in laravel 9 can be implement easily using the laravel file and storage providers.In a website Image uploading can be used in multiple places like set up a profile picture to providing the documents. Laravel 9 provides robust functionality to upload and process the image…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version