Calling AJAX directly after page loads

It is a simple example how to call AJAX request right as page loads, not requiring user to do any action. This examples correctly handles both expected result and AJAX error and puts it into selected element.

In view put following Javascript code:

<script type="text/javascript">
$(function()
{
    function showAJAXResult(div, msg){jQuery(div).slideUp(function(){jQuery(div).html(msg).slideDown()});}

    <?php
        echo(CHtml::ajax(array
        (
                'cache'=>false,
                'url'=>array('orders/ajaxgetparams', 'id'=>$model->ID),
                'success'=>'function(html){showAJAXResult("#section_2_div", html)}',
                'error'=>'function(xhr, desc, er){showAJAXResult("#section_2_div", xhr.responseText)}'
        )));
    ?>
});
</script>

And here is controller code, a sample server-side response for above shown client-side request:

public function actionAJAXGetParams($id)
{
    if(app()->request->isAjaxRequest)
    {
        $sql = 'SELECT * FROM table_name';

        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);
        $dataReader = $command->query();
        $rows = $dataReader->readAll();

        $this->renderPartial('view_file_for_rendering_ajax_result', array('rows'=>$rows));

        app()->end();
    }
    else throw new CException('Operation allowed only in AJAX mode!');
}

Put together works like a charm.

Leave a Reply