I am struggling to get prefill data while editing document in php

<?php
session_start();
include '../config.php';

// Check if user is logged in
if (!isset($_SESSION['id'])) {
    echo ("<script LANGUAGE='JavaScript'>
            window.alert('Please Login First..!!!');
            window.location.href='index.php';
           </script>");
    exit();
}

$id = $_GET['id'];
$query = "SELECT * FROM tbl_associate_master WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
$associate = $result->fetch_assoc();
$stmt->close();

include 'intelmark_head.php';
include 'intelmark_sidebar.php';
?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Edit Associate</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Edit Associate</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <form id="associateForm">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title">Edit Associate</h3>
                    </div>
                    <div class="card-body">
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="associate_id" value="<?php echo $associate['id']; ?>">
                        <div class="mine_box">
                            <div class="row">
                                <!-- Associate Name -->
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="associate_name">Associate Name</label>
                                        <input type="text" class="form-control" id="associate_name"
                                            name="associate_name" placeholder="Enter Associate Name"
                                            value="<?php echo $associate['associate_name']; ?>" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <!-- Contact Names in one line -->
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="contact_name1">Contact Name 1</label>
                                        <input type="text" class="form-control" id="contact_name1"
                                            name="contact_name1" placeholder="Enter Contact Name 1"
                                            value="<?php echo $associate['contact_name1']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="contact_name2">Contact Name 2</label>
                                        <input type="text" class="form-control" id="contact_name2"
                                            name="contact_name2" placeholder="Enter Contact Name 2"
                                            value="<?php echo $associate['contact_name2']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="contact_name3">Contact Name 3</label>
                                        <input type="text" class="form-control" id="contact_name3"
                                            name="contact_name3" placeholder="Enter Contact Name 3"
                                            value="<?php echo $associate['contact_name3']; ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div id="addressContainer">
                            <div class="address_mine_box" style="margin-top: 20px;">
                                <div class="address-group">
                                    <div class="row">
                                        <!-- Address -->
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="address1_line1">Address</label>
                                                <input type="text" class="form-control" id="address1_line1"
                                                    name="address_line1[]" placeholder="Enter Address Line 1"
                                                    value="<?php echo $associate['address1_line1']; ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="address1_line2">Address Line 2</label>
                                                <input type="text" class="form-control" id="address1_line2"
                                                    name="address_line2[]" placeholder="Enter Address Line 2"
                                                    value="<?php echo $associate['address1_line2']; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <!-- Country, State, City -->
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="address1_country">Country</label>
                                                <select class="form-control" id="address1_country" name="country[]">
                                                    <option value="">Select Country</option>
                                                    <!-- Add PHP code to fetch and display countries -->
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="address1_state">State</label>
                                                <select class="form-control" id="address1_state" name="state[]">
                                                    <option value="">Select State</option>
                                                    <!-- Add PHP code to fetch and display states based on country -->
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="address1_city">City</label>
                                                <select class="form-control" id="address1_city" name="city[]">
                                                    <option value="">Select City</option>
                                                    <!-- Add PHP code to fetch and display cities based on state -->
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <!-- Pincode -->
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="address1_pincode">Pincode</label>
                                                <input type="text" class="form-control" id="address1_pincode"
                                                    name="pincode[]" placeholder="Enter Pincode"
                                                    value="<?php echo $associate['address1_pincode']; ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label> </label><br>
                                                <button type="button" class="btn btn-secondary add-address-btn">Add Address</button>
                                                <button type="button" class="btn btn-danger remove-address-btn" style="display: none;">Remove Address</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Add more addresses as needed, similarly -->
                        </div>
                        <div class="mine_box">
                            <div class="row">
                                <!-- Phone -->
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="phone1">Phone</label>
                                        <input type="text" class="form-control" id="phone1" name="phone1"
                                            placeholder="Enter Phone" value="<?php echo $associate['phone_number1']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="phone2">Phone</label>
                                        <input type="text" class="form-control" id="phone2" name="phone2"
                                            placeholder="Enter Phone" value="<?php echo $associate['phone_number2']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="phone3">Phone</label>
                                        <input type="text" class="form-control" id="phone3" name="phone3"
                                            placeholder="Enter Phone" value="<?php echo $associate['phone_number3']; ?>">
                                    </div>
                                </div>

                                <!-- Email -->
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="email1">Email</label>
                                        <input type="email" class="form-control" id="email1" name="email1"
                                            placeholder="Enter Email" value="<?php echo $associate['email1']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="email2">Email</label>
                                        <input type="email" class="form-control" id="email2" name="email2"
                                            placeholder="Enter Email" value="<?php echo $associate['email2']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="email3">Email</label>
                                        <input type="email" class="form-control" id="email3" name="email3"
                                            placeholder="Enter Email" value="<?php echo $associate['email3']; ?>">
                                    </div>
                                </div>
                                <!-- Website -->
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="website">Website</label>
                                        <input type="text" class="form-control" id="website" name="website"
                                            placeholder="Enter Website" value="<?php echo $associate['website']; ?>">
                                    </div>
                                </div>
                            </div>
                            <!-- Remark -->
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="remark">Remark</label>
                                    <textarea class="form-control" id="remark" name="remark"
                                        placeholder="Enter Remark"><?php echo $associate['remarks']; ?></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">Update</button>
                        </div>
                    </div>
            </form>
        </div>
    </section>
</div>

<?php include 'intelmark_footer.php'; ?>
<style>
.mine_box {
    border: 1px solid #ddd;
    padding: 20px;
    margin: 20px 0;
    border-radius: 5px;
    background-color: #f9f9f9;
}
.address-group {
    margin-top: 20px;
    margin-bottom: 20px;
}
.address_mine_box {
    border: 1px solid #ddd;
    padding: 20px;
    margin: 20px 0;
    border-radius: 5px;
    background-color: #f9f9f9;
    margin-top: 20px;
}
.remove-address-btn {
    margin-top: 10px;
}
</style>

<script>
$(document).ready(function() {
    // Fetch countries and pre-select values
    $.ajax({
        url: 'city_state_country_fetch.php',
        type: 'GET',
        data: { type: 'countries' },
        success: function(response) {
            if (response.error) {
                console.error("Error fetching countries: " + response.error);
                return;
            }

            var countries = response;
            var options = "<option value=''>Select Country</option>";
            for (var i = 0; i < countries.length; i++) {
                options += "<option value='" + countries[i].id + "'>" + countries[i].country_name + "</option>";
            }
            $("[name='country[]']").html(options);

            // Pre-select country values
            var countryIds = [<?php echo $associate['address1_country_id']; ?>, <?php echo $associate['address2_country_id']; ?>, <?php echo $associate['address3_country_id']; ?>];
            $("[name='country[]']").each(function(index) {
                if (countryIds[index]) {
                    $(this).val(countryIds[index]).change();
                }
            });
        },
        error: function(xhr, status, error) {
            console.error("Error fetching countries: ", error);
        }
    });

    // Fetch states based on selected country and pre-select values
    $(document).on('change', '[name="country[]"]', function() {
        var countryId = $(this).val();
        var $stateSelect = $(this).closest('.address-group').find('[name="state[]"]');
        var $citySelect = $(this).closest('.address-group').find('[name="city[]"]');
        $citySelect.html("<option value=''>Select City</option>"); // Reset city dropdown

        $.ajax({
            url: 'city_state_country_fetch.php',
            type: 'GET',
            data: { type: 'states', country_id: countryId },
            success: function(response) {
                if (response.error) {
                    console.error("Error fetching states: " + response.error);
                    return;
                }

                var states = response;
                var options = "<option value=''>Select State</option>";
                for (var i = 0; i < states.length; i++) {
                    options += "<option value='" + states[i].id + "'>" + states[i].state_name + "</option>";
                }
                $stateSelect.html(options);

                // Pre-select state values
                var stateIds = [<?php echo $associate['address1_state_id']; ?>, <?php echo $associate['address2_state_id']; ?>, <?php echo $associate['address3_state_id']; ?>];
                var stateId = stateIds[$("[name='country[]']").index(this)];
                if (stateId) {
                    $stateSelect.val(stateId).change();
                }
            },
            error: function(xhr, status, error) {
                console.error("Error fetching states: ", error);
            }
        });
    });

    // Fetch cities based on selected state and pre-select values
    $(document).on('change', '[name="state[]"]', function() {
        var stateId = $(this).val();
        var $citySelect = $(this).closest('.address-group').find('[name="city[]"]');

        $.ajax({
            url: 'city_state_country_fetch.php',
            type: 'GET',
            data: { type: 'cities', state_id: stateId },
            success: function(response) {
                if (response.error) {
                    console.error("Error fetching cities: " + response.error);
                    return;
                }

                var cities = response;
                var options = "<option value=''>Select City</option>";
                for (var i = 0; i < cities.length; i++) {
                    options += "<option value='" + cities[i].id + "'>" + cities[i].city_name + "</option>";
                }
                $citySelect.html(options);

                // Pre-select city values
                var cityIds = [<?php echo $associate['address1_city_id']; ?>, <?php echo $associate['address2_city_id']; ?>, <?php echo $associate['address3_city_id']; ?>];
                var cityId = cityIds[$("[name='state[]']").index(this)];
                if (cityId) {
                    $citySelect.val(cityId);
                }
            },
            error: function(xhr, status, error) {
                console.error("Error fetching cities: ", error);
            }
        });
    });

    // Add more address fields
    $(document).on('click', '.add-address-btn', function() {
        if ($(".address-group").length < 3) {
            var addressGroup = $(".address_mine_box:first").clone();
            addressGroup.find("input").val("");
            addressGroup.find("select").val("");
            addressGroup.find(".add-address-btn").hide();
            addressGroup.find(".remove-address-btn").show();
            $("#addressContainer").append(addressGroup);
        } else {
            alert("You can only add up to 3 addresses.");
        }
    });

    // Remove address fields
    $(document).on('click', '.remove-address-btn', function() {
        $(this).closest('.address_mine_box').remove();
    });

    // Handle form submission
    $("#associateForm").submit(function(event) {
        event.preventDefault();
        var formData = $(this).serialize();

        $.ajax({
            url: 'intelmark_associate_master_action.php',
            type: 'POST',
            data: formData,
            success: function(response) {
                alert('Associate updated successfully');
                window.location.href = 'intelmark_associate_master.php';
            }
        });
    });
});

</script>

associate_edit.php
<?php
include '../config.php';

header('Content-Type: application/json');

$type = $_GET['type'];
$data = [];

try {
    if ($type == 'countries') {
        $query = "SELECT id, country_name AS name FROM tbl_countries_master";
    } elseif ($type == 'states' && isset($_GET['country_id'])) {
        $country_id = intval($_GET['country_id']);  // Ensure it's an integer
        $query = "SELECT id, state_name AS name FROM tbl_states_master WHERE country_id = $country_id";
    } elseif ($type == 'cities' && isset($_GET['state_id'])) {
        $state_id = intval($_GET['state_id']);  // Ensure it's an integer
        $query = "SELECT id, city_name AS name FROM tbl_cities_master WHERE state_id = $state_id";
    } else {
        throw new Exception('Invalid request');
    }

    $result = mysqli_query($conn, $query);

    if (!$result) {
        throw new Exception('Database query error: ' . mysqli_error($conn));
    }

    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }

    echo json_encode($data);
} catch (Exception $e) {
    // Log the error message to a file or any other logging mechanism
    error_log($e->getMessage());

    // Send a JSON response with the error message
    echo json_encode(['error' => $e->getMessage()]);
}
?>

I have an associate database with country_id, state_id, and city_id fields. When I try to edit a record, all data is prefilled correctly, but the dropdown options for country, state, and city are not automatically selected based on the prefilled data. How can I ensure that these dropdowns show the selected values corresponding to the prefilled data when editing a record?

8

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật