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 : (some people saying autofill cant work with depednt drop down list, if that true then guide me)

 <table class="table table-bordered">
                    <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>
        
          			
      	<td><input type="text" class="qty form-control text-end" name="qty[]" id="ccc" onfocus="Calc(this);"></td>
	<td><input type="text" class="price form-control text-end" name="price1[]" id="ddd"   onfocus="Calc(this);" ></td>
	
           <td class="NoPrint"><button type="button" class="btn btn-success"  style="line-height: 1;" onclick="BtnDel(this)">x</button></td>
			
                      </tr>   </tbody> </table>
// code for depednt drop down list
<script>
        $(document).ready(function() {
            $("#country").on('change', function() {
                var countryid = $(this).val();

                $.ajax({
                    method: "POST",
                    url: "response.php",
                    data: {
                        id: countryid
                    },
                    datatype: "html",
                    success: function(data) {
                        $("#state").html(data);
                        $("#city").html('<option value="">Select Machine</option');

                    }
                });
            });
            $("#state").on('change', function() {
                var stateid = $(this).val();
                $.ajax({
                    method: "POST",
                    url: "response.php",
                    data: {
                        sid: stateid
                    },
                    datatype: "html",
                    success: function(data) {
                        $("#city").html(data);

                    }

                });
            });
        });
    </script>
// code for autofill in the form

<script>

		// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(row) {
  let str = row.querySelector(".city").value;
  if (str.length == 0) {
      row.querySelector(".qty").value = "";
    row.querySelector(".price").value = "";
   
    return;
  } else {
    // Creates a new XMLHttpRequest object
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {

      // Defines a function to be called when
      // the readyState property changes
      if (this.readyState == 4 &&
        this.status == 200) {

        // Typical action to be performed
        // when the document is ready
        var myObj = JSON.parse(this.responseText);

        // Returns the response data as a
        // string and store this array in
        // a variable assign the value
        // received to first name input field

       
        row.querySelector(".qty").value = myObj[0];
        row.querySelector(".price").value = myObj[1];
  
      }
    };

    // xhttp.open("GET", "filename", true);
    xmlhttp.open("GET", "gfg.php?user_id=" + str, true);

    // Sends the request to the server
    xmlhttp.send();
  }
}
	</script> 

// Response .php file which handle dependent drop down list

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

Why do you have 2 different DB files?

Please investigate prepared statements. This code is very susceptible to injection attacks. (What happens to your database if I send $_POST['id'] to be 0; SELECT * FROM mysql.user or 0; DROP TABLE mysql.* or…or…)
Also dont select * if you only want 2 values, unless your entire table is 2 columns.

Nothing you have there immediately looks like it should stop it from working… have you checked what the network tab is telling you you’re sending/receiving from the PHP?

EDIT: Oh wait, you’re dynamically adding rows. Yeah you’ll have to use event delegation, and not use ID’s for things you’re going to duplicate. ID must be unique. Classes can share.

yes i already replaced IDs with classes as i am using dynamic rows. As i said every thing working fine. When there is one drop down list, everything is working fine,

but when I added two more drop down list, and make them depend on each other the the real problem start.
as code have two parts . one is that these three dependent list extract value which is working fine and second is that to generate autofill in empty text fields on the basis of 3rd depednt llist. and its not working

squints

You wanna try that sentence again?

Regardless, for dynamically created rows, you’re going to need event delegation to attach the event above the dynamic level, probably to the table itself.

Understanding Event Delegation | jQuery Learning Center

oh sorry i replace it for autofill code inside first file. yes u are right that i have to replace ids for depdnt drop down list code as well but i think problem wil not solve by just replacing is by classes . look at

// code for autofill in the form

<script>

		// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(row) {
  let str = row.querySelector(".city").value;
  if (str.length == 0) {
      row.querySelector(".qty").value = "";
    row.querySelector(".price").value = "";
   
    return;
  } else {
    // Creates a new XMLHttpRequest object
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {

      // Defines a function to be called when
      // the readyState property changes
      if (this.readyState == 4 &&
        this.status == 200) {

        // Typical action to be performed
        // when the document is ready
        var myObj = JSON.parse(this.responseText);

        // Returns the response data as a
        // string and store this array in
        // a variable assign the value
        // received to first name input field

       
        row.querySelector(".qty").value = myObj[0];
        row.querySelector(".price").value = myObj[1];
  
      }
    };

    // xhttp.open("GET", "filename", true);
    xmlhttp.open("GET", "gfg.php?user_id=" + str, true);

    // Sends the request to the server
    xmlhttp.send();
  }
}
	</script> ~~~

ia m using only on db connection file, db1 is just key board error

Hi @itumarnazir!! I have analyzed this coding and I have a few suggestions for you, I hope this coding could help you fix the autofill feature not working with dependent drop down lists.

1 – Using the same ID attribute for multiple elements is not a good practice. You know ID should be unique for each element. Use class instead of id for such elements with repetitive names and functionality. Such as you can use class=“country” instead of id=“country” for the select element that contains the type options. This will also make it easier to access the elements using jQuery selectors, such as (“.country”)insteadof(“#country”).

2 – You are using onchange event of the city select element to call the GetDetail function, that is supposed to autofill the quantity and price fields based on the user selection but in your coding this function in not defined anywhere, You need to write this function and include it in your script tag or in a separate JavaScript file. You also need to pass the row parameter to this function, as you are using it inside the function body to access the elements in the same row.


<script> function GetDetail(row) { // Get the user id from the city select element let user_id = row.querySelector(“.city”).value; // Check if the user id is not empty if (user_id.length > 0) { // Create a new XMLHttpRequest object let xmlhttp = new XMLHttpRequest(); // Define a function to be called when the readyState property changes xmlhttp.onreadystatechange = function() { // Check if the request is completed and successful if (this.readyState == 4 && this.status == 200) { // Parse the JSON response from gfg.php let result = JSON.parse(this.responseText); // Assign the quantity and price values to the corresponding input fields row.querySelector(“.qty”).value = result[0]; row.querySelector(“.price”).value = result[1]; } }; // Open a GET request to gfg.php with the user id as a query parameter xmlhttp.open(“GET”, “gfg.php?user_id=” + user_id, true); // Send the request xmlhttp.send(); } else { // Clear the quantity and price fields if the user id is empty row.querySelector(“.qty”).value = “”; row.querySelector(“.price”).value = “”; } } </script>

1 Like

You are missing a closing curly brace for the GetDetail function. You should add it at the end of the script tag.

Thirdly you also missed to add coding for Calc function. You need to write this function and include it in your script tag or in a separate JavaScript file.

Afterwards you need to add a hidden input field with name=“total” in each row of your table, so that you can store and send the total amount for each item to your server-side script. You can add this field after the price input field, like this:

<td><input type=“text” class=“price form-control text-end” name=“price1[]” id=“ddd” onfocus=“Calc(this.closest(‘tr’))”></td> <td><input type=“hidden” name=“total[]” value=“”></td>

1 Like

shrug code works for me with the first row (again, for the dynamic rows, you’ll need some event delegation):
Mad Reads? (codepen.io)

So its something in your environment or returns.

1 Like

yes i have dynamic rows, and yes for that i need event delegation but dont know how :frowning:

Thanks alot sir!

shrug code ??? how

Did you read the link I posted about event delegation?
Did you understand it?
Did you implement it?

Then I would advise sleeping so your brain can function.

If you’ve tried to implement it, what does your code look like now?

1 Like

Yeah, i kind of had the feeling thats where this thread was headed, based on your code’s… shall we say, incohesiveness.

I wish you luck in convincing other people to do your work for you, especially to your own deadlines. When you have genuine questions and make the effort to learn, we’ll be here.
(For clarity to those that follow, including moderators, I also received a private solicitation to “just do the code for me”.)

4 Likes

@m_hutley!! I wholeheartedly agree with your sentiments. It’s crucial for each of us to take responsibility for our own learning and work. While we’re all here to support each other when we encounter problems, the initiative to understand and write the code should come from the person who needs it. This way, we all grow and learn together. Thanks for bringing this up and maintaining the integrity of our coding community.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.