'Dynamic dropdown Ajax PHP request

I'm trying to make a dynamically populated drop down in a form for location selection. I have scoured stack in other posts that ask similar questions and some websites but my second dropdown is always blank.

The first dropdown is populated via a MySQL query.

Form section

<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->getDistricts();
        ?>
    </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>

Ajax request

<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: "GET",
                    url: "includes/scripts/ajax/ajax_county.php",
                    data: { district : $("#dists").val() },
                    success: function(reply){
                        $("#councils").html(reply);
                        console.log(reply);
                    },
                    error: function() {
                        alert('Error occured');
                    }
            });
            
        });
    });
</script>

ajax_county.php

<?php
if(isset($_POST['district'])){
    $district = $_POST['district'];

    $dist = new Database();
    $dist->getCouncils($district);

}else{
    echo"fail";
}

?>

Database.php

<?php
class Database{
public static $host = "localhost";
public static $dbName = "domaidandb";
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_portugal where dist_parent_id = $id");
            $stmt->execute();
            
            $councils = $stmt->fetchAll();
            foreach ($councils as $row):
            echo "<option value=".$row['council_id'].">".$row['council_name']."</option>";
            endforeach; 
    }
}

Before the district is changed. Before district is changed

After the district changed. After the district changed

A print screen from the Google Chrome console network tab (after the district select was changed) A print screen from the Google Chrome console network tab

A print of the console log The console log The request is sent and a response is recieved but the response is blank, the Content-Length: 0, there is nothing in it. Maybe there is something wrong with my php?

I've built my own MVC model and I have routing set up on my pages, would this affect the AJAX request?, i.e

Route::set('home', function(){
        Index::CreateView('Index');
    });

Any ideas on how i can populate the dropdown



Solution 1:[1]

It seems to be a problem with the database. You can use mysqli_report(MYSQLI_REPORT_ALL); and see what is happening Check ajax_county.php the while at the end, it can create an infinite loop. You are using Database(), so maybe it is possible you can have a problem there.

Anyway, I prepared a code that should be work for you,

Please notice I've modified again your code for just for testing purposes (only using the getCouncils() function and the database query is a bit different)

index.php

<?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>

Database.php

<?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; 
    }
}

ajax_county.php

<?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>";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1