Dynamic Select Box using Jquery Ajax php mysqlHow to create a dynamic select box using jquery ajax php and mysql
Database
CREATE TABLE `rme_city` ( `idarea` int(11) NOT NULL, `city` varchar(255) NOT NULL, `contryid` varchar(200) NOT NULL DEFAULT '' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `rme_city` (`idarea`, `city`, `contryid`) VALUES (1, 'Oakland', '4'), (2, 'San Diego', '4'), (21, 'Birmingham', '1'), (22, 'Montgomery', '1'); ALTER TABLE `rme_city` MODIFY `idarea` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Select Box using Jquery Ajax php mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
</head>
<body>
<p>State :
<select name="country" class="country select" style="width:250px" >
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4" selected>California</option>
<option value="5">Colorado</option>
<option value="6">Connecticut</option>
<option value="7">Florida</option>
<option value="8">Georgia</option>
</select></p>
<p>City :
<select name="city" style="width:250px" class="city select">
<option value="" selected="selected" >Please Select Your Area</option>
</select></p>
</body>
</html>
city.php
<?php
$mysqli = new mysqli('localhost','root','','testingdb');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
if($_POST['id'])
{
$id=$_POST['id'];
$results = $mysqli->query("SELECT * FROM rme_city where contryid='$id' ORDER BY city ASC");
while($row = $results->fetch_assoc()) {
$id=$row['idarea'];
$data=$row['city'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>