Auto fill not working with dependent drop down list

i am using autofill feature in my form, it was working fine when there was one drop down list. But when I hav to use multiple dependent list, then its stop taking values automatically from gfg.php. here is my complete code. (Auto fill in Form working fine when there is one depednt list (Select Machine) ) but when I added two parents list, (Service and Type) with reponse.php file then autofil stop working. here is my code :

                    <thead class="table-success" style="background-color: #3fbbc0;">
                      <tr>
            <th width="15%"><center>Type</th> 
                        <th width="15%"><center>Service</th> 
                        <th width="15%"><center>Machine</th>                   
            <th width="5%"><center>Qty</th>                       
            <th width="10%"><center>Rate</th>
            <th width="5%"></th>                                               
                         <button type="button" class="btn btn-sm btn-success" onclick="BtnAdd()">Add Item</button>                         
                        </th>
</tr>
                    </thead>
                    <tbody id="TBody">
                      <tr id="TRow" class="d-none">

 <td><Select  class="country form-control text-end" name="country[]" id = "country" >
<option value=""> Select Type</option>
                <?php
                include('db1.php');
                $query = "select * from country";
                // $query = mysqli_query($con, $qr);
                $result = $con->query($query);
                if ($result->num_rows > 0) {
                    while ($row = mysqli_fetch_assoc($result)) {
                ?>
                <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
                <?php
                    }
                }     ?>    </select> </td>

 <td><Select  class="state form-control text-end" name="state[]" id = "state">
<option value="">select Service</option></select></td>

 <td><Select  class="city form-control text-end" name="city[]" id = "city"   onchange="GetDetail(this.closest('tr'))">
<option value="">Select Machine</option></select></td>

</td>~~~
// Response.php file which handle dependent list is below :
<?php
include_once("db.php");
if (!empty($_POST["id"])) {
    $id = $_POST['id'];
    $query = "select * from state where country_id=$id";
    $result = mysqli_query($con, $query);
    if ($result->num_rows > 0) {
        echo '<option value="">Select Service</option>';
        while ($row = mysqli_fetch_assoc($result)) {
            echo '<option value="' . $row['id'] . '">' . $row['state'] . '</option>';
        }
    }
} elseif (!empty($_POST['sid'])) {
    $id = $_POST['sid'];
    $query1 = "select * from city where state_id=$id";
    $result1 = mysqli_query($con, $query1);
    if ($result1->num_rows > 0) {
        echo '<option value="">Select Machine</option>';
        while ($row = mysqli_fetch_assoc($result1)) {
            echo '<option value="' . $row['id'] . '">' . $row['city'] . '</option>';
        }
    }
}

//gfg.php to get autofill values from database

<?php

// Get the user id
$user_id = $_REQUEST['user_id'];

// Database connection
$con = mysqli_connect("localhost", "root", "", "hmis");

if ($user_id !== "") {
    
    // Get corresponding first name and
    // last name for that user id   
    $query = mysqli_query($con, "SELECT  qty1, uprice FROM machine1 WHERE user_id ='$user_id'");

    $row = mysqli_fetch_array($query);

    // Get the first name
    $ccc = $row["qty1"];
    $ddd = $row["uprice"];
    
    
    
    
}

// Store it in a array
$result = array("$ccc", "$ddd");

// Send in JSON encoded form
$myJSON = json_encode($result);
echo $myJSON;
?>

The HTML and PHP parts you’ve provided seem fine. But, the key to making the dependent dropdown and autofill work lies in the JavaScript that links everything together.

Here’s a simple example of how the JavaScript might look:

$(document).ready(function() {
    // When value changes on the "Type" dropdown
    $("#country").change(function() {
        var id = $(this).val();
        // Make Ajax call to response.php with 'id'
        $.ajax({
            url: 'response.php',
            type: 'post',
            data: {id: id},
            dataType: 'json',
            success:function(response) {
                // Reset the "Service" dropdown
                $("#state").empty();
                $("#state").append('<option value="">Select Service</option>'); 
                // Populate the "Service" dropdown
                for(var i = 0; i < response.length; i++) {
                    $("#state").append('<option value="'+ response[i]['id'] +'">'+ response[i]['state'] +'</option>');
                }
            }
        });
    });

    // When value changes on the "Service" dropdown
    $("#state").change(function() {
        var id = $(this).val();
        // Make Ajax call to response.php with 'sid'
        $.ajax({
            url: 'response.php',
            type: 'post',
            data: {sid: id},
            dataType: 'json',
            success:function(response) {
                // Reset the "Machine" dropdown
                $("#city").empty();
                $("#city").append('<option value="">Select Machine</option>'); 
                // Populate the "Machine" dropdown
                for(var i = 0; i < response.length; i++) {
                    $("#city").append('<option value="'+ response[i]['id'] +'">'+ response[i]['city'] +'</option>');
                }
            }
        });
    });

    // When the value changes on the "Machine" dropdown
    $("#city").change(function() {
        // This is where you can call your autofill logic using 'gfg.php' if needed
    });
});

  1. Ensure you have included jQuery for the above code to work in your page.
  2. Ensure your response.php returns a valid JSON response. You may have to modify the response.php code to send JSON responses using json_encode().
  3. Ensure that there is no name or ID conflict, as it can break the functioning of the JavaScript. If you dynamically generate rows, you need a more elaborate system to handle unique IDs and events.
  4. Ensure proper error handling in your JavaScript so if there’s any problem with the AJAX request, it can be diagnosed easily.
Sponsor our Newsletter | Privacy Policy | Terms of Service