Show sub-options based on selected main option in Codeigniter by ajax

681 views Asked by At

I would like when I select the cats option that only the breed of cats appears, such as the Siamese example. If I select dog, I only want to get the breed of dogs, such as Pitbull and others.

Can you help me with the code, it tells me to use jquery, but how is it done I am just learning?

<div class="form-group">
    <div class="row">
        <div class="col-12 col-sm-6">
            <label for="especie">Especie</label>
            <select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
                <option value="">Seleccionar especie</option>
                <?php foreach ($especie as $row) {?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
                <?php }?>
            </select>
        </div>
        <div class="col-12 col-sm-6">
            <label for="raza">Raza</label>
            <select class="form-control" id="id_raza" name="id_raza">
                <option value="">Seleccionar raza</option>
                <?php foreach ($raza as $row) {?>
                    <option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
                <?php }?>
            </select>
        </div>
    </div>
</div>

Screenshot of first dropdown

Screenshot of second dropdown

2

There are 2 answers

0
KUMAR On BEST ANSWER

According to your Question you want Dynamic dependant drop down list in codeigniter with ajax / jQuery.

PHP VIEW :

<div class="col-12 col-sm-6">
        <label for="especie">Especie</label>
        <select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
            <option value="">Seleccionar especie</option>
            <?php foreach ($especie as $row) {?>
                <option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
            <?php }?>
        </select>
    </div>

<div class="col-12 col-sm-6">
        <label for="raza">Raza</label>
        <select class="form-control" id="id_raza" name="id_raza">
         <!-- Data here will be auto populated by ajax -->

            </select>
    </div>

Controller :

public function get_data()
           {
                $id_especie = $this->input->post("id_especie");
     $SUbCatdata = $this->db->get_where('tableName',array('id'=>$id_especie))->result_array();
            $option ="<option selected disabled value=''>Select Name</option>";
              foreach($SUbCatdata as $row)
              {
                 $option.="<option value='".$row['id']."'>".$row['nombre']."</option>";
              }
               echo $option;
           }

jQuery / Ajax :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
    $(document).ready(function() {
        $("#id_especie").on("change",function(){
        var id_especie = $(this).val();
     
        $.ajax({
             url : "<?php echo base_url('Controller/get_data') ?>",
             type: "post",
             data: {"id_especie":id_especie},
             success : function(data){
                //alert(data);
        $("#id_raza").html(data);
             }
        });
    });
    
    </script>   
        

Note : For more info regarding change()

https://api.jquery.com/change

1
Samuel Asor On

If I understand you correctly, you want to create a sub-dropdown list that is dependent on the selection of another (main) dropdown list. If this is the case, here's what you need to do.

First, you need to create a file that contains code that will fetch results based on what is supplied. That is (in your example), if the main category is "dogs", it will query the database for all "species" of dogs, and return the result. Something like this:

Category Controller

class Category_controller extends CI_Controller{
    // Get Subcategory method
    public function get_subcategory()
    {
        // Check if input ($_GET or $_POST) exists
        if ( $this->input->post_get() )
        {
            $main_cat_id = $this->input->post_get('mainid'); // main category id
            
            // Perform your db query here to get the subcategory of the main cat
            // Echo the result after performing a foreach loop like you did in the 
            // html file. <option value="value_id">value name</option>
            $result = ""; // store empty value first
            foreach ($dbresult as $value)
            {
                $result .= '<option value="$value['id']">$value['nombre']</option>';
            }
            echo $result;
        }
    }
}

SubCategory.js

$(document).ready(function() {
    $('select[name="id_especie"]').on('change', function() {
        var catid = $(this).val(); // will get the value attribute of the selected main category

        // Perform ajax request
        $.ajax({
            url: 'url-to-the-subcategory-controller', // remember to set this in your config/routes.php file
            method: 'POST',
            cache: false,
            data: {mainid: catid},
            dataType: 'html',
            success: function(data) {
                $('select#id_raza').html(data); // update the subcategory dropdown
            },
            error: function(data) {
                console.log(data);
            }
        });
    })
});

So, your second select box select#id_raza show look like so in your view file:

<div class="col-12 col-sm-6">
        <label for="raza">Raza</label>
        <select class="form-control" id="id_raza" name="id_raza">
            <option value="">Seleccionar raza</option>
            <!-- Data here will be auto populated by ajax -->
        </select>
    </div>