Reputation: 115
I need use set_select but the options of the select2 are called from controller with ajax. How can I do?
My controller:
public function getCategoryByLocation()
{
$location_id = $this->input->post('location_id');
$locationscats = $this->Categories_model->getCategorylocal($location_id);
if(count($locationscats) > 0)
{
$select = '';
$select .= '<option value="">'.$this->lang->line('text_none').'</option>';
foreach ($locationscats as $locationscat) {
$select .='<option value="'.$locationscat->category_id.'">'.$locationscat->name.'</option>';
}
echo json_encode($select);
}else{
$select = '';
$select .= '<option value="">'.$this->lang->line('text_none').'</option>';
echo json_encode($select);
}
}
My Model:
public function getCategorylocal($location_id)
{
$query = $this->db->get_where('categories', array('location_id' => $location_id));
return $query->result();
}
My View:
<select name="parent_id" id="category" class="form-control">
<option value=""><?php echo lang('text_none'); ?></option>
</select>
And the Ajax call..
$(document).ready(function() {
$('#input-location').on('change', function() {
var location_id = this.value;
$.ajax({
url:"<?php echo site_url("/categories/getCategoryByLocation"); ?>",
type: "POST",
data: {'location_id' : location_id},
dataType: 'json',
success: function(data){
$('#category').html(data);
},
error: function(){
alert('Error occur...!!');
}
});
});
$("#input-location").trigger('change');});
Is possible used set_select from the controller?... I'm using set_select in the views but no in controller...
Upvotes: 0
Views: 611
Reputation: 1585
I don't see where you using set_select in your view but since you're returning an HTML fragment of options, you can just return the view without doing json encoding.
$this->load->view('view_that_builds_options', $this->locationscats);
Or build the $select var and echo that...
public function getCategoryByLocation() {
$this->load->helper('form');
$location_id = $this->input->post('location_id');
$locationscats = $this->Categories_model->getCategorylocal($location_id);
$select .= '<option value="">'.$this->lang->line('text_none').'</option>';
if(count($locationscats) > 0) {
foreach ($locationscats as $locationscat) {
$select .='<option value="'.$locationscat->category_id.'">'
// assume your select is named 'category' by the id='category'.
$select .= set_select('category', $NoIdeaWhatValueYouAreCheckingForGoesHere);
$select .= $locationscat->name.'</option>';
}
}
echo $select;
}
Upvotes: 1