//ads:
?>
Dynamic dropdown Ajax PHP request
PHP Snippet 1:
<?php
include('Database.php');
?>
<label for="" class="block">District
<select id="dists" name="prop_district" class="full block" required>
<option selected disabled>District...</option>
<?php
$dist = new Database();
$dist->getCouncils(1);
?>
</select>
</label>
<label for="" class="block">Council
<select id="p_councils" name="prop_council" class="full block" required>
<option selected disabled>Council...</option>
</select>
</label>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#dists").change(function(){
var id=$(this).val();
$.ajax({
type: "POST",
url: "ajax_county.php",
data: { district: id },
success: function(html){
console.log(html);
$("#p_councils").html(html);
}
});
});
});
</script>
PHP Snippet 2:
<?php
class Database{
public static $host = "localhost";
public static $dbName = "yourdatabase";
public static $username = "root";
public static $password = "";
private static function connect() {
$pdo = new PDO("mysql:host=".self::$host.";dbname=".self::$dbName.";charset=utf8", self::$username, self::$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
//GET COUNCILS
public static function getCouncils($id) {
$con = new Database();
$con->connect();
$stmt = self::connect()->prepare("SELECT * FROM councils where council_id = $id");
$stmt->execute();
$councils = $stmt->fetchAll();
foreach ($councils as $row):
echo "<option value=".$row['council_id'].">".$row['council_name']."</option>";
endforeach;
}
}
PHP Snippet 3:
<?php
$dist = $_POST['district'];
$servername = "localhost";
$username = "root";
$password = "";
//mysqli_report();
// Create connection
$con = new mysqli($servername, $username, $password);
$con->select_db("teststack");
$stmt = $con->prepare("SELECT * FROM councils WHERE dist_parent_id = ?");
$stmt->bind_param( 'i' , $dist);
$stmt->execute();
$dists = $stmt->get_result();
$dists = $dists->fetch_all(MYSQLI_ASSOC);
echo '<option selected disabled>Councils...</option>';
foreach($dists as $r){
echo "<option value=".$r['council_id'].">".$r['council_name']."</option>";
}