I encounter this block of error message yet I can't figure out where gone wrong with the code.
POST http://localhost/get_state.php 500 (Internal Server Error)
send @ jquery-2.1.1.min.js:4ajax @ jquery-2.1.1.min.js:4
getState @ index.php:14onchange @ index.php:34
ListPicker._handleMouseUp @ about:blank:542
The database contains two tables which called Country & States. When country is selected, it will show states which belongs to that country.
Below are the codes.
File name: index.php
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
$country=array();
$sql ="SELECT * FROM country";
$result=$conn->query($sql);
}
?>
<html>
<head>
<TITLE>jQuery Dependent DropDown List - Countries and States</TITLE>
<head>
<style>
body{width:610px;}
.frmDronpDown {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;}
.demoInputBox {padding: 10px;border: #F0F0F0 1px solid;border-radius: 4px;background-color: #FFF;width: 50%;}
.row{padding-bottom:15px;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
while($country=$result->fetch_assoc()){
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
</div>
</body>
</html>
File name: get_state.php
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST["country_id"])) {
$sql ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $conn->query($sql);
?>
<option value="">Select State</option>
<?php
while($state=$result->fetch_assoc()){
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
}
}
?>