1

i have a problem with filling dropdown data from ajax script. here's my controller:

public function ajax_get_kota($idProv='')
{
    $kota = $this->data['namaKota'] = $this->registrasi_model->get_nama_kota($idProv);
    echo json_encode($kota);
}

here's my model:

public function get_nama_kota($idProv='')
{
    $query = $this->db->query('SELECT id_kab, nama FROM kabupaten WHERE id_prov = '.$idProv.' ORDER BY nama ASC');
    return $dropdowns = $query->result();
}

and view:

<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">        
    <?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
    <div class="col-sm-3">
       <?php
            $atribut_kota = 'class="form-control dropKota"';
            echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
            set_validation_icon('Kota');
        ?>
    </div>
    <?php if (form_error('Kota')) : ?>
        <div class="col-sm-9 col-sm-offset-3">
            <?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
        </div>
    <?php endif ?>

    <script>
        $(document).ready(function () {
            $(".dropProv").on("change", function(){
                var idProv = $(this).val();
                var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
                var kota = [];
                $.ajax({
                    url: baseUrl,
                    data: kota,
                    success: function(datas){
                        $(".dropKota").select2({
                             placeholder: "Pilih Kota",
                             data: datas
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error");
                    }
                });
            });
        });
    </script>
</div>

what i'm trying to do here is how to pass this data that im getting from ajax:

[{"id_kab":"5103","nama":"KAB. BADUNG"},{"id_kab":"5106","nama":"KAB. BANGLI"},{"id_kab":"5108","nama":"KAB. BULELENG"},{"id_kab":"5104","nama":"KAB. GIANYAR"},{"id_kab":"5101","nama":"KAB. JEMBRANA"},{"id_kab":"5107","nama":"KAB. KARANGASEM"},{"id_kab":"5105","nama":"KAB. KLUNGKUNG"},{"id_kab":"5102","nama":"KAB. TABANAN"},{"id_kab":"5171","nama":"KOTA DENPASAR"}]

into the dropdown dropKota. those data is dynamically generated when another dropdown value is changed.

current result:

enter image description here

select2 requires a specific format so it can be properly displayed in dropdown

var data = [{ id: 0, text: 'enhancement' } //something like this

how do i do this?

1
  • U have to map the array like this: $data = ArrayHelper::map(Clients::find()->asArray()->all(), 'cid', function($model, $defaultValue) { return $model['cid'] . " - " . $model['first_name'] . " " . $model['middle_name'] . " " . $model['last_name']; } ); Commented Aug 25, 2016 at 11:09

4 Answers 4

1

U have to do like this :

 $.ajax({
                url: url,
                type: "POST",
                async: false,
                data: {id: id},
                success: function(data) {
                    var data_array = $.parseJSON(data);
                    $.each(data_array.emp, function(key, value) {
                        $('#Your_drop_down_id').append($('<option>', {
                            value: key,
                            text: value,
                        }));
                    });

                }
            });

U have to parse the data(JSON to array) and then use $.each for looping all values.

Sign up to request clarification or add additional context in comments.

1 Comment

i have updated my question, how to format the array data into select2 specific format? thank you for your help
1

Try this:

success: function(datas){
    var data = JSON.parse(datas);

    var options = '<select name="dd_name"><option>Select</option>';
    for(i=0; i<data.length; i++)
    {
        options += '<option value="'+ data.col_name +'">'+ data.col_id +'</option>';
    }
    options += '</select>';

    $('#div_id').html(options);   // where #div_id is the id of a div in which this drop down is required.
},

2 Comments

this one only give option select, thanks for the respond
i updated my code, see the current result, i move the select2 JS into the ajax success function, the dropdown is able to load data but it's messed up
0

Change $.ajax call as below

$.ajax({
    url: baseUrl,
    data: kota,
    dataType: "JSON",
    success: function(datas){
        var s= document.getElementById('<Element Id>');
        s.eampty();
        $.each(datas, function(index, el) {
            s.options[index]= new Option(index, el);
        });
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("error");
    }
});

dataType: "JSON", will respond output of ajax call in json format. Replace <Element Id> with element id to which you want to add data.

Full Source

<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">        
    <?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
    <div class="col-sm-3">
       <?php
            $atribut_kota = 'class="form-control dropKota"';
            echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
            set_validation_icon('Kota');
        ?>
    </div>
    <?php if (form_error('Kota')) : ?>
        <div class="col-sm-9 col-sm-offset-3">
            <?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
        </div>
    <?php endif ?>

    <script>
        $(document).ready(function () {
            $(".dropKota").select2({
                placeholder: "Pilih Kota"
            });
            $(".dropProv").on("change", function(){
                var idProv = $(this).val();
                var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
                var kota = [];
                $.ajax({
                    url: baseUrl,
                    data: kota,
                    dataType: "JSON",
                    success: function(datas){
                        var s= document.getElementById('<Element Id>');
                        s.eampty();
                        $.each(datas, function(index, el) {
                            s.options[index]= new Option(index, el);
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error");
                    }
                });
            });
        });
    </script>
</div>

Comments

0

Finally, i found the solution after asking here and there, so here's the solution:

JS and select2 script:

<script>
        $(document).ready(function () {
            $(".dropProv").on("change", function(){
                var idProv = $(this).val();
                var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
                var kota = [];
                $.ajax({
                    url: baseUrl,
                    dataType: 'json',
                    success: function(datas){
                        //since select2 need a specific format u need to do this
                        var kota = $.map(datas, function (obj) {
                            obj.id = obj.id || obj.id_kab; // replace id_kab with your identifier
                            obj.text = obj.text || obj.nama // replace nama with your identifier
                            return obj;
                        });
                        $(".dropKota").select2({ //change dropKota into your element
                            placeholder: "Pilih Kota",
                            data: kota
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error");
                    }
                });
            });
        });
    </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.