AJAX for Country/State DropDownList - Run on page load?

I have a list of countries that pulls from the database, which then makes an AJAX request to load in the States/Provinces related to it. It works fine when you change the country, but when the page first loads, the states are not loaded in. How should I make this AJAX call when the page loads?

Create Page

View _form.php for create and edit




    <div class="row">

        <?php echo $form->labelEx($model,'country'); ?>

        <?php

              echo $form->dropDownList($model,'country_id',CHtml::listData(Countries::model()->findAll(),'id','name'),

                    array(

                        'ajax' => array(

                            'type' => 'POST',

                            'url' => CController::createUrl('mymodelname/dynamicStates'),

                            'update' => '#MyModelName_'.'state_id'

                        )

                    )

              );

        ?>

        <?php echo $form->error($model,'CountryID'); ?>

    </div>


    <div class="row">

        <?php echo $form->labelEx($model,'state'); ?>

        <?php echo $form->dropDownList($model,'state_id',array($model->state_id => $model->state));?>

        <?php echo $form->error($model,'state_id'); ?>

    </div>



As far as I know there is no "Yii way" to accomplish this. However if you put the javascript below in your view file it will solve the problem:

[html]

$(document).ready(function(){

$.ajax({

type: 'POST',


data: {id: &#036;('#MyModelName_country_id').val()},


url: '&lt;?php echo CController::createUrl('mymodelname/dynamicStates') ?&gt;',


success: function(data){


            &#036;('#MyModelName_state_id').html(data)


        }

})

})

[/html]

The above script will send a post request with the currently selected country set to the id variable to your controller and outputs the result in the dropdown box. If that output is not html than you need to build the options from the JSON.

That’s exactly what I was looking for! :rolleyes:

Thanks a lot!