Spread the love

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:

Code Repo:

2 thoughts on “Show dropdown list from ajax response in jQuery

  1. Hi,
    Thank you for this.

    Question:
    Can I use this with Materialize so that I can put it all in a ‘Container’ and also place the Dropdowns in a Grid format?

Leave a Reply