I am writing a shop application, and I have a question.
As you know ajax in Yii looks like
<?php
echo CHtml::ajaxLink(
'',
array("cart/add/id/$item->id"),
array(
'update'=>'#cart',
),
array('class' => "button_basket")
);
?>
This code updates the div with id = cart
. How can I update the other elements on the page? For example on the Cart page, I am removing via ajax one item and I need to update the Total price, what is the best way to do this?
For this you'll need to write some javascript, preferably a function that will read the response from the server, and make changes in the ui accordingly.
If you go through the documentation for ajaxLink();
, you'll see that the third parameter is ajaxOptions which takes the options of jQuery's ajax method. Therefore you can write a callback function for the success event. And in this function you can make changes to your ui.
Sample code:
<?php
echo CHtml::ajaxLink(
'',
array("cart/add/id/$item->id"),
array(
// 'update'=>'#cart', this will be ignored when you have success callback
'success'=>'js:successFunctionName',
),
array('class' => "button_basket")
);
?>
Somewhere in the current view you can use registerScript
to output the function to the view:
Yii::app->clientScript->registerScript('scriptname','
function successFunctionName(data, textStatus, jqXHR){
// write awesome javascript to change ui
}
');