0

Okay My problem is little complex which I am unable to solve. I already have two select boxes in which the options are coming from Database Mysql through php. Like when I select an option in Select Box#1, Select Box#2 gets updated through ajax and displays the options against SelectBox#1 from MYSQL Database. I am able to store the values from those two in database as well.

Problem : Now the problem is that I want a button like "Add New" that should create same two select boxes with same functionality the number of times i click Add New Button. Example: I filled the original two select boxes, then I click Add New and two new select boxes gets generated.. I fill them and again click Add New and two more select boxes gets generated so total of 6 select boxes with same first Select Box options but options in Second Select Box may differ according to the option selected in first select box. Now, two things I need help in:-

1. How to perform this Add New button thing that generates select boxes with same functionality as the original ones i.e Select Option from First Select Box, Second Select Box gets auto updated according to the option selected in first select box and the options are fetched from Database.

2. How do I read and store those values selected from new fields? I am able to read and store values that were passed from the original two select boxes but how about the new ones? Any unique names or ids of new select boxes I generate through button or some sort of array etc?

Here is my code that I used for my first two select boxes:-

HTML FILE-TOP

    function load_country()
    {
    $connection = new mysqli("localhost","root","","test");
    $query = "SELECT * FROM country";
    $result = mysqli_query($connection,$query);

    while($row = mysqli_fetch_array($result))
    {
        $output .= '<option value="'.$row["c_id"].'">'.$row["c_name"].'</option>' ;
    }
    return $output;

    }

HTML FILE-INSIDE

 <form method="post">
       <p> <select name="country" id="country">

        <option value="">Select Country</option>

        <?php echo load_country() ?>

        </select> </p>

        <p> <select name="city" id="city">

        <option value="">Select City</option>

        </select> </p>

        <input type="submit" name="submit" value="submit">

        </form> 

Jquery/Ajax Function that updates the Second Select Option:-

$(document).ready(function(){
 $('#country').change(function(){
  var country_id = $(this).val();
   $.ajax({
    url:"fetch_city.php",
    method:"POST",
    data:{
        "c_id":country_id
    },
    dataType: "text",
    success:function(data)
    {
     $('#city').html(data);
    }
   });
  });
 });
</script>

PHP File used by Ajax to Update Second Select Box:-

$output = '';
$query = "SELECT * FROM cities WHERE country_id = '{$_POST["c_id"]}'";

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

$output = '<option value="">Select City</option>';

while($row = mysqli_fetch_array($result))
{
    $output .= '<option value="'.$row["city_id"].'">'.$row["city_name"].'</option>'   ;
}

echo $output;
OzMan
  • 1
  • 5
  • The first step will be to modify your logic to work with a class, not an id. Ids should not be repeated within a given document, by web standards. And then your second step will be to find the contextual relationship between each pair of select boxes, and if one does not exist, create it, so future logic will be easy to implement – Taplar Dec 18 '19 at 19:02
  • @Taplar to be honest, i am a newbie in javascript, ajax and jquerry. I know php well but for this functionality is totally out of my knowledge :( – OzMan Dec 18 '19 at 19:07
  • It's the same approach as with developing php, or any language really. You have to break down the problem into smaller steps, and tackle the steps. That's why I've given you two steps. There are many potential questions/issues related to your question, which makes it lean towards being too broad. However, I wanted to point you towards a starting point that should get you at least going in the general right direction. – Taplar Dec 18 '19 at 19:10

1 Answers1

0

First Change the HTML into something like this, use classes and ids for finding objects better:

<form method="post">
    <div id="form-area">
        <div class="select-box" id="box_1">
            <p>
                <select class="country" name="country[]">
                    <option value="">Select Country</option>
                            <?php echo load_country() ?>
                </select>
            </p>
            <p>
                <select class="city" name="city[]">

                    <option value="">Select City</option>

                </select>
            </p>
        </div>
    </div>
    <button id="add_new" type="button"> [+] </button>

    <input type="submit" name="submit" value="submit">
</form>

javascript:

$(document).on("change", ".country", function() {
    var current_box = $(this).parent().closest('div').attr('id');
    var country_id = $(this).val();
    $.ajax({
        url: "fetch_city.php",
        method: "POST",
        data: {
            "c_id": country_id
        },
        dataType: "text",
        success: function(data) {
            $('#' + current_box).find(".city").html(data);
        }
    });
});
    var id = 1;
    $('#add_new').click(function() {
        id++;
        $(".select-box:last").clone().attr("id", "box_" + id).appendTo("#form-area");
    });

After that, you should handle Array input in PHP form destination code. In your case it should be something like this:

$cities = $_REQUEST['city'];
$cuontries = $_REQUEST['cuontry'];

foreach( $cuontries as $key => $cuontry ) {
 $row[] = [ "cuontry" => $cuontry , "city" => $cities[$key] ];
}

This array is as same as form array that you created with [+] button in HTML

Kamran
  • 523
  • 6
  • 18