Ajax

Show List on Select in Ajax jQuery

How to show List on Select in Ajax jQuery –

Step – 1: First create database table named “course_list” given as bellow –

  • In this expamle, we create two dependent dropdown. If we select course type then all related course name show in other dropdown box accodring to selected “id” in ajax.

Step 2: Create database connection file named “connectiondb.php” –

<?php
	$servername = "localhost";
	$username = "root";
	$password = "";
	$dbname = "testDatabase";

	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);
	// Check connection
	if ($conn->connect_error) {
	  die("Connection failed: " . $conn->connect_error);
	}
?>

Step – 3 : Create Dropdown list –

<?php 
	include("connectiondb.php");
?>
<!doctype html>
<html>
  <head>
    <title>Show List on Select in Ajax Jquery</title>
	<script src="https://codeloveguru.com/master-library/js/jquery.min.js"></script>
	<script>	
		$(document).ready(function(){		
			$("#coursetype").change(function () {
				var ctype = $(this).val();
				if(ctype){
					$.ajax({
						type: 'POST',
						url: 'ajaxprocess.php',
						data: {coursetype: ctype},
						success: function (data) {                                                                                   
							$('#coursename').html(data);                                                                                   
						},
						error: function () {
							console.log("error");
						}
					});
				} else {
					$('#coursename').html('<option value="">--- Select ---</option>');				
				}			
			});
		});
	</script>	
  </head>
	<body>    
		<p>
			<label for="coursetype">Course Type : </label>                                
			<select name="coursetype" id="coursetype">
				<option value="">--- Select ---</option>
				<option value="1">Undergraduate Course</option>
				<option value="2">Postgraduate Course</option>										
			</select>
		</p>
		<p>
			<label for="coursename">Course Name : </label>                                
			<select name="coursename" id="coursename">
				<option value="">--- Select ---</option>		
			</select>
		</p>	
	</body>
</html>

Step – 4 : Create ajax & PHP file named “ajaxprocess.php” given as bellow –

<?php

include("connectiondb.php");

	$ctype = isset($_POST['coursetype']) ? $_POST['coursetype'] : '';
	$qrs = "SELECT course_id, course_name, id FROM course_list where course_id=$ctype";
	$resdatas = mysqli_query($conn, $qrs);

	if (mysqli_num_rows($resdatas) > 0) {
	  $sub_caste_data='<option value="">--- Select ---</option>';
	  while($rowD = mysqli_fetch_assoc($resdatas)) {    
		$sub_caste_data .= '<option value="'.$rowD["id"].'">'.$rowD["course_name"].'</option>';				 
	  }
	  echo $sub_caste_data; exit;
	}  
?>

Show List on Select in Ajax jQuery

One thought on “Show List on Select in Ajax jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *

× How can I help you?