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 showAJAXResult(div, msg)

'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)}'

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

public function actionAJAXGetParams($id)
$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));

else throw new CException('Operation allowed only in AJAX mode!');

Put together works like a charm.

Leave a Reply