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);
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
Just take a div or whatever in which you want to append your data. Id in your case is Officer_InCharge,
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
In ajax, you just have to add html into select box. For this you have to put below code in ajax.
In controller, you have to put below conditions
In model:
Just send array data via model :
First of all you need to send json encode data from controller to ajax.So make some changes in controller as follows :
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:
try this