0

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

1 Answer 1

2

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>";
}
Sign up to request clarification or add additional context in comments.

7 Comments

Hi Alvin, thanks for your answer but the "County" select box still just goes blank after the "District" select is changed.
Hi Dominic, I recommend you use mysqli_report() if you don't have it activated to see why the query is not working. Probably is related with the database connection, I've updated the answer with the way I used to connect it. I hope it helps `
Thanks for your reply. I don't seem to be getting any data from the php file back to my ajax request on the page. I checked the connection seperatley, the mysql query is fine and also the connection. I just don't seem to be able to get the data back. Could my routing (Route::set) have anything to do with it? Im working in an MVC model
If I add: ``` success: function(reply){ console.log(reply); alert(reply); }, error: function() { alert('Error occured'); } ``` The console says: ** jquery.min.js:4 XHR finished loading: POST "localhost/domaidan/Database.php". ** And the alert just says: "Localhost says" Its blank
Can you confirm the ajax_county.php file is retrieving the data? Opening the file in the browser with $dist = SOMEVALIDVALUE; and seeing if it shows the values from the $dist specified
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.