简体   繁体   中英

codeigniter - dependent dropdown with jquery and ajax post

view : learning_view.php

Here is the first dropdown which I am populating from database.

    <select name = 'category' id = 'category'>
        <option value="">-- Select Category --</option>
        <?php foreach($category as $item){ ?>
        <option value="<?php echo $item->id_cat; ?>"><?php echo $item->name; ?></option>
        <?php } ?>
    </select>
    <br><br>

What I want is to populate another dropdown which is dependent on the first dropdown. For that I have used the jQuery ajax post.

second dropdown:

    <select name = 'type' id = 'type'>
        <option value="">-- Select Type --</option>
        <?php foreach($type as $item){ ?>
        <option value="<?php echo $item->id_type; ?>"><?php echo $item->name; ?></option>
        <?php } ?>
    </select>
    <br><br>

ajax post:

    jQuery(document).ready(function(){
      $("#category").change(function() {
        var category_id = {"category_id" : $('#category').val()};
        console.log(category_id);

        $.ajax({
          type: "POST",
          data: category_id,
          url: "<?= base_url() ?>learning/dependent_dropdown",

          success: function(data){

            $.each(data, function(i, data){
            console.log(data.name);
            console.log(data.id_type)
            });
           }
         });
       });
     });

controller : learning.php

   public function dependent_dropdown()
   {
       if(isset($_POST['category_id']))
       {
           $this->output
           ->set_content_type("application/json")
           ->set_output(json_encode($this->learning_model->getType($_POST['category_id'])));
       }
   }

The data is coming from the database after ajax post which I checked by

    console.log(data.name);
    console.log(data.id_type)

in the console.

But couldn't able to figure out how to use the data in the second dropdown of my view.

I mean how can i populate the second dropdown with the data i have received after ajax post.

I found a solution to my problem by modifying the success function of the ajax post:

success: function(data) {
    $.each(data, function(i, data) {
        $('#type').append("<option value='" + data.id_type + "'>" + data.name + "</option>");
    });
}

Which append the value into the drop down.

<select name="type" id="type">
    <option value="">-- Select Type --</option>
</select>

I just gave the id of the select block into the success function of the ajax post and appended the value. It works but there is a problem which is when I change the selection of the first dropdown new value appears but the values which were showing for the previous selection doesn't go away.

Here is some modification of your answer

success: function(data)
{
    $('#type').html('<option value="">-- Select Type --</option>');

        $.each(data, function(i, data){
        $('#type').append("<option value='"+data.id_type+"'>"+data.name+"</option>");
        });
}

It will show only new items.

view code:

<select id="category" name="prod_cat" class="form-control col-md-7 col-xs-12 category">
                    <?php if($category)
                        foreach ($category as $cat)
                        {
                    ?>
                            <option value="<?php echo $cat->cat_id;?>"><?php echo $cat->cat_title; ?></option>
                    <?php
                        }
                    ?>
                </select>

ajax code:

`

$(document).ready(function() {
    $('.category').change(function(){
      $.ajax({
        type: "POST",
        url: "<?php echo base_url();?>Product_admin/getSub",
        data:{id:$(this).val()}, 
        beforeSend :function(){
      $(".subcat option:gt(0)").remove();  
      $('.subcat').find("option:eq(0)").html("Please wait..");
        },                         
        success: function (data) {
          /*get response as json */
           $('.subcat').find("option:eq(0)").html("Select Subcategory");
          var obj=jQuery.parseJSON(data);
          $(obj).each(function()
          {
           var option = $('<option />');
           option.attr('value', this.value).text(this.label);           
           $('.subcat').append(option);
         });  
          /*ends */
        }
      });
    });
  });

`

Controller:

public function getSub()
{
      $result=$this->db->where('cat_id',$_POST['id'])
                    ->get('tbl_subcategory')
                    ->result();
    $data=array();
    foreach($result as $r)
    {
        $data['value']=$r->subcat_id;
        $data['label']=$r->subcat_title;
        $json[]=$data;


    }
    echo json_encode($json);

I too had same issue.. This is what I did..Worked well https://github.com/eboominathan/Dependent-Dropdown-in-Codeigniter-3.0.3

i have done the same thing today. when i call the url via ajax i simply do the load-view procedure and load all the data in another small view file holding only select and option statment and a query to display data , and under the main view i create a div with id #divid and simply on success of ajax i did

$('#divid').html(data);

and that view will be displayed on the main page.

hopefully i make u understand.

On success function write down this code. It will append your data in second dropdown:

$.ajax({
    type: "POST",
    data: category_id,
    url: "<?= base_url() ?>learning/dependent_dropdown",
    success: function(data) {
        $.each(data, function(i, data) {
            var opt = $('<option />'); 
            opt.val(data.id_type);
            opt.text(data.name);
            $('#your_second_dropdown_id_name').append(opt);
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM