article

Sunday, February 8, 2015

Dropdown with dynamic content (Ajax/CodeIgniter)

Dropdown with dynamic content (Ajax/CodeIgniter)  

Controller:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Ajax_sample extends CI_Controller {
/* file: application/controllers/ajax_sample.php */
 
    function index(){
        $data = array();
 
        $data['arr_field1'] = array(
            1 => 'option 1',
            2 => 'option 2',
            3 => 'option 3',
        );
 
        $this->load->helper('form');
 
        $this->load->view('sample_dropdown', $data);
    }
 
    function get_dropdown_values($filter){
 
        $this->load->model('test_model');
 
        $result = $this->test_model->get_options($filter);
 
        $this->load->helper('form');
 
        echo form_dropdown('field2', $result, NULL, 'id="field2"');
    }
}
Model:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
class Test_model extends CI_Model {
/* file: application/models/test_model.php */
 
    function get_options($filter=''){
 
        switch($filter){
            case 1:
                $arr = array('option A', 'option B', 'option C');
            break;
            case 2:
                $arr = array('option D', 'option E', 'option F');
            break;
            case 3:
                $arr = array('option G', 'option H', 'option I');
            break;
            default: $arr = array('option Z');
        }
 
        return $arr;
    }
}
View:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
/* file: application/views/sample_dropdown.php */
 
 
    echo form_open('insert');
 
        echo form_dropdown('field1', $arr_field1, NULL, 'id="field1" onchange="load_dropdown_content($(\'#field2\'), this.value)"');
 
        echo form_dropdown('field2', array('0' => '...'), NULL, 'id="field2"');
 
    echo form_close();
 
?>
  
<script type="text/javascript">
 
function load_dropdown_content(field_dropdown, selected_value){
    var result = $.ajax({
        'url' : '<?php echo site_url('ajax_sample/get_dropdown_values'); ?>/' + selected_value,
        'async' : false
    }).responseText;
    field_dropdown.replaceWith(result);
}
 
</script>
URL : http://localhost/codeIgniter_3_1_10/ajax_sample

Related Post