skip to Main Content

I need to Select Department first from a drop down and then need to load officers in that particular department in another drop down list. I am doing this in Codeigniter.

View
(Second Drop down where I have to load the Oficers Names. I have already loaded values for Department drop down, and upon department selection this dropdown should get select values)

<div class="form-group">
   <select name="Officer_InCharge" id="Officer_InCharge" class="form-control input-lg">
      <!--<option value="">Select officer</option>-->
   </select>
</div>

My AJAX

<script>
  $(document).change(function(){
    $("#Officer_Dept").click(function(){
      var Dept = $('#Officer_Dept').val();
      if (Dept != '') 
      {
        $.ajax({
          url:"<?php echo base_url();?>Crud/fetch_officers",
          method:"POST",
          data:{Dept:Dept},
          //dataType: 'json',
          success:function(data)
          {

            alert(data);

            var options = "";
             for (var i = 0; i < data.length; i++) {
                 options += "<option>" + data[i].user_name + "</option>";
             }
             $("#Officer_InCharge").html(options);
          }
        })
      }
  });
});
</script>

The AJAX call is successful, the problem I face is that with appending the ajax response to Officer selecting Drop Down. Those values display in alert

alert(data);

enter image description here
But Not being displayed in the drop down.

My Controller

public function fetch_officers()
    {
        if ($this->input->post('Dept')) 
        {
            echo $this->Crud_model->fetch_dept_officers($this->input->post('Dept'));

        }
    }

My Model

function fetch_dept_officers($Dept)
    {
        $this->db->where('user_dept',$Dept);
        $this->db->order_by('user_name', 'ASC');
        $query = $this->db->get('tbl_users');

        $output = '<option value="">Select Officer</option>';
          foreach($query->result() as $row)
          {
            $output .= '<option value="'.$row->user_id.'">'.$row->user_name.'</option>';
            //$output += "<option value='"+$row->user_id+"'>"+$row->user_name+"</option>";
            //$output .= '<option>'.$row->user_name.'</option>';
            //formoption += "<option value='"+val+"'>"+val+"</option>";

            //
            //
          }
          return $output;
          //return $query->result();
    }

Appreciate if anyone can sort this out. Thanks in Advance.

5

Answers


  1. Just take a div or whatever in which you want to append your data. Id in your case is Officer_InCharge,

    $("#Officer_InCharge").append(options);
    
    Login or Signup to reply.
  2. You pass only result array of query from your model to controller and from controller you can return the fetch_dept_officers result and in AJAX success call you can append option

    MY Model

      function fetch_dept_officers($Dept)
            {
                $this->db->where('user_dept',$Dept);
                $this->db->order_by('user_name', 'ASC');
                $query = $this->db->get('tbl_users');
    
                return $query->result();
            }
    
    Login or Signup to reply.
  3. In ajax, you just have to add html into select box. For this you have to put below code in ajax.

    <script>
      $(document).change(function(){
        $("#Officer_Dept").click(function(){
          var Dept = $(this).val();
          if (Dept != '') 
          {
            $.ajax({
              url:"<?php echo base_url();?>Crud/fetch_officers",
              method:"POST",
              data:{Dept:Dept},
              //dataType: 'json',
              success:function(data)
              {
    
                $("#Officer_InCharge").html(data);
              }
            })
          }else{
             alert('Please select Department');
         }
      });
    });
    </script>
    

    In controller, you have to put below conditions

    public function fetch_officers()
        {
            if ($this->input->post('Dept')) 
            {
                echo $this->Crud_model->fetch_dept_officers($this->input->post('Dept'));
    
            }else{
                echo "<option>No Officer Available.</option>";
            }
    
        }
    

    In model:

    function fetch_dept_officers($Dept)
        {
            $this->db->where('user_dept',$Dept);
            $this->db->order_by('user_name', 'ASC');
            $query = $this->db->get('tbl_users');
            $optionsResult=$query->result();
    
        if(count($optionsResult)>0){
        $output = '<option value="">Select Officer</option>';
    
          foreach($optionsResult as $row)
          {
            $output .= '<option value="'.$row->user_id.'">'.$row->user_name.'</option>';
            //$output += "<option value='"+$row->user_id+"'>"+$row->user_name+"</option>";
            //$output .= '<option>'.$row->user_name.'</option>';
            //formoption += "<option value='"+val+"'>"+val+"</option>";
    
            //
            //
          }
        }else{
         $output="<option>No Officer available</option>";
        }
          return $output;
          //return $query->result();
    }
    
    Login or Signup to reply.
  4. Just send array data via model :

    function fetch_dept_officers($Dept)
        {
            $this->db->where('user_dept',$Dept);
            $this->db->order_by('user_name', 'ASC');
            $query = $this->db->get('tbl_users')->result_array();
    
            return $query ;
    
        }
    

    First of all you need to send json encode data from controller to ajax.So make some changes in controller as follows :

    public function fetch_officers()
    {
       if ($this->input->post('Dept')) 
       {
         $result_data=$this->Crud_model->fetch_dept_officers($this->input->post('Dept'));
         echo json_encode($result_data); //send encoded data
        }
     }
    

    in ajax you need to first parse that json and set data in html with the help of jquery.
    please find the ajax code below:

    $.ajax({
       url:"<?php echo base_url();?>Crud/fetch_officers",
       method:"POST",
       data:{Dept:Dept},
       success:function(data) {
          var parse_data = JSON.parse(data); //parse encoded data
          $.each(parse_data,function(index,value){
             $("#Officer_InCharge").append("<option>" + value.user_name + "</option>");   
          });
       }
    })
    
    Login or Signup to reply.
  5. try this

    $('#Officer_Dept').change(function () {
        var Dept = $('#Officer_Dept').val();
        $.ajax({
            type: 'GET',
            url: base_url + '/Crud/fetch_officers',
            data: {
                Dept:Dept
            },
            success: function (data) {
                var html = '';
                $.each(data.data, function (i, value) {
                    html += ('<option value="' + value.id + '">' + value.user_name + '</option>');
    
                });
                $("#Officer_InCharge").html(html);
            }
        });
    });
    
    //in controller
    
       function getInchargeOfficer(Request $request) {
            $inchargeOfficerArray = ModelName::where('dept', $request->Dept)->get();
            if (!empty($inchargeOfficerArray)) {
                return response()->json(['data' => $inchargeOfficerArray]);
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search