Show subcategory by select category PHP

In this example Mobile is a category. After choose mobile category we can see the subcategory in another select box.


database.php

<?php
	$servername = "localhost";
	$username = "root";
	$password = "";
	$db="example";
	$conn = mysqli_connect($servername, $username, $password,$db);
?>

index.php

<?php
include 'database.php';
$result = mysqli_query($conn,"SELECT * FROM category");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Category</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	<form>
		<div class="form-group">
		  <label for="sel1">Category</label>
		  <select class="form-control" id="category">
		  <option value="">Select Category</option>
		    <?php
			while($row = mysqli_fetch_array($result)) {
			?>
				<option value="<?php echo $row["id"];?>"><?php echo $row["category_name"];?></option>
			<?php
			}
			?>
			
		  </select>
		</div>
		<div class="form-group">
		  <label for="sel1">Sub Category</label>
		  <select class="form-control" id="sub_category">
			
		  </select>
		</div>
	</form>
</div>
<script>
$(document).ready(function() {
	$('#category').on('change', function() {
			var category_id = this.value;
			$.ajax({
				url: "get_subcat.php",
				type: "POST",
				data: {
					category_id: category_id
				},
				cache: false,
				success: function(dataResult){
					$("#sub_category").html(dataResult);
				}
			});
		
		
	});
});
</script>
</body>
</html>

get_subcat.php

 <?php
	include 'database.php';
	$category_id=$_POST["category_id"];
	$result = mysqli_query($conn,"SELECT * FROM subcategory where category_id=$category_id");
?>
<option value="">Select SubCategory</option>
<?php
while($row = mysqli_fetch_array($result)) {
?>
	<option value="<?php echo $row["id"];?>"><?php echo $row["subcategory_name"];?></option>
<?php
}
?>