3

I am using kartik select2 widget in my yii2 basic app. now i have to display province names in select2 widget on ajax call. It is working fine if i put it directly in form. however not working with ajax call.

Here are my form fields:

<?= $form->field($model, 'role')->dropDownList(
    ArrayHelper::map(SubAdminRoles::find()->all(), 'id', 'role_name'),
    [
        'prompt' => 'Select Role',
        'onchange' => '
            if($(this).val() != 3) {
                $( "#user_area" ).html("showLoading");
                $.post( "fetch-area-list?id='.'"+$(this).val(), 
                function(data) {
                    $( "#user_area" ).html(data);
                })
            }'
    ]
    ) ?>

 <div id="user_area">

</div>

And here is my action code

public function actionFetchAreaList($id) {
   // $this->layout = 'none';
    $data = [];
    if($id == 1) {
        $provinceList = \app\modules\adminpanel\models\ProvinceMaster::findAll(['status' => 1, 'is_deleted' => 0]);

        foreach($provinceList as $obj) {
            $data[$obj['id']] = $obj['province_name'];
        }
        //print_r($data);
        //exit;
    } else if($id == 2) {
        $subDistrictList = \app\modules\adminpanel\models\SubDistrictMaster::findAll(['status' => 1, 'is_deleted' => 0]);

        foreach($subDistrictList as $obj) {
            $data[$obj['id']] = $obj['sub_district_name'];
        }
    }

    echo '<label class="control-label">Select Province</label>';
    echo Select2::widget([
        'name' => 'state_2',
        'value' => '1',
        'data' => $data,
        'options' => ['multiple' => true, 'placeholder' => 'Select Province']
    ]);
    exit;
}

now when i try to get it through ajax i comes with display:none property so i am not able to show my select2 box.

I Also tried changing display:none to display:block in select2 class. In that case i got the select box, but is simple html multiple select box not select2 widget.

How to get it from controller using ajax call?

Thanks in advance.

Ninja Turtle
  • 1,293
  • 2
  • 24
  • 50

2 Answers2

0

It is bad practice to render html inside action. In your case widget requires related JS for initialization. But it will not include in your response. Move all your html to view area-list and render using following code:

public function actionFetchAreaList($id) {
    $this->layout = false;

    // ... preparing data

    return $this->renderAjax('area-list', [
        // ... some view data
    ]);
}

Method renderAjax renders a named view and injects all registered JS/CSS scripts and files. It is usually used in response to AJAX Web requests.

IStranger
  • 1,868
  • 15
  • 23
  • Thanks but i already tried this. It redirects me to area-list action – Ninja Turtle Sep 23 '16 at 05:27
  • This code should not redirect to any page. Probably ajax response contains some js error. Debug it using browser console at enabled "preserve log" option. It prevents refreshing the console output after redirect – IStranger Sep 23 '16 at 05:37
0

I also have similar project like this. I have 2 combobox (using select2). When select a district from the first combobox. It will call an ajax request to get province list and fill into the second combobox. Here is my solution:

  1. Using Select2 widget as normally in form
  2. Using javascript to call ajax request and change data of the second combobox. My controller response data in json format.

    $('#district-selector').on('change', function() {
        var districtId = $(this).val();
        var url = $(this).attr('tb_href');
        $('#province-selector').html('');
        $.get(
            url,
            {
                city_id: districtId
            },
            function(response) {
                if (response.error == 0 && response.data.length) {
                    $('#province-selector').append(new Option('', ''));
                    $.each(response.data, function() {
                        console.log(this.id + '--' + this.title);
                        var newOption = new Option(this.title, this.id);
                        $('#province-selector').append(newOption);
                    });
                }
                $('#province-selector').trigger('change');
            }
        );
    });
    

Demo: demo link

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
namdt55555
  • 409
  • 1
  • 3
  • 14