loading widget through ajax

I’m having trouble loading widget properly through ajax.

I’m trying to add a fully functional datepicker to my view dynamically.

This is the button/code that calls the controller action to render the datepicker:




    <div id="datepicker_div"></div>

    <?= Html::a('Add datepicker', 'javascript:;', [

        'onclick' =>'

            $.post( "/users/load_datepicker", function( data ) {

                $( "#datepicker_div" ).html( data );

            });

        '

    ]) ?>



This is the controller action that gets called:




    public function actionLoad_datepicker(){

        echo DatePicker::widget([

            'name' => 'dp_6',

            'type' => DatePicker::TYPE_BUTTON,

            'value' => '23-Feb-1982',

            'pluginOptions' => [

                'format' => 'dd-M-yyyy'

            ]

        ]);

    }



The returned data contains the html for the element but not the javascript needed for it to function properly.

What would be the correct way of implementing this? I’ve tried getting it to work through renderPartial() from controller, but with no luck…

Any help will be greatly appreciated!

Thanks! :)

Hi, ajax response sends only the html of the datepicker widget in your case.

One work around is to load the datepicker widget in the view file and see the javascript (inline as well as the files) which is coming with it.

You may use the same javascript code in your page where you will load the datepicker widget using ajax.

Another work around is to hide the widget initially when loading the view page. instead of ajax, you may show the widget using jQuery.