<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<?php
$citiesList = $db->query("SELECT * FROM cities")->fetchAll(PDO::FETCH_ASSOC);
?>
<form action="" method="POST" onsubmit="return false;" id="newaddressform">
<div class="customer-login text-left">
    <h4 class="title-1 title-border text-uppercase mb-30">YENİ ADRES EKLE</h4>
    <input type="text" placeholder="Adres başlık" name="title">
    <select name="sehir" id="city">
        <option value="">Şehir Seçiniz</option>
        <?php
        foreach ($citiesList as $value){
            echo '<option value="'.$value['CityID'].'">'.$value['CityName'].'</option>';
        }
        ?>
    </select>
    <select id="town" name="ilce">
        <option value="">İlçe Seçiniz</option>
    </select>
    
    <script type="text/javascript">
    $(document).ready(function(){
        $("#town").hide(); // Başlangıçta ilçe select'i gizli
        
        $("#city").change(function(){
            var cityId = $(this).val();
            if(cityId) {
                $.ajax({
                    type: "POST",
                    url: "inc/ajax.php",
                    data: {"cityId": cityId}, // Tutarlı parametre adı
                    success: function(response) {
                        $("#town").show();
                        $("#town").html(response);
                    },
                    error: function(xhr, status, error) {
                        console.log("Hata: " + error);
                    }
                });
            } else {
                $("#town").hide();
            }
        });
    });
    </script>

    <input type="text" placeholder="Mahalle, Cadde, sokak, bina no, daire no" name="content">
    <button type="submit" onclick="newaddress();" id="newaddres" class="button-one submit-button mt-15">ADRES EKLE</button>
</div>      
</form>

$CityId = isset($_POST['CityId']) ? intval($_POST['CityId']) : 0;

$townList = $db->prepare("SELECT * FROM town WHERE CityID = ?");
$townList->execute([$CityId]);
$towns = $townList->fetchAll(PDO::FETCH_ASSOC);

foreach ($towns as $town) {
    echo '<option value="'.$town['TownID'].'">'.$town['TownName'].'</option>';
}