Reputation: 113
I am currently new to the Yii framework, and I was wondering if anyone had good example or experience with Javascript to assist me creating a ajax submit button. The entire purpose of this submit button is to favorite the current page and send the data to the / needed. The label of the button must change depending on the information from the database ( button label -> favorite or un-favorite ).
Here the current functionality from my basic button. I would like to do the next step and start using ajax. If anyone is interested in teaching a newbie. I would be up for the challenge.
<div>
<?php echo CHtml::button('Favorite', array('submit'=>array('user/favoritePage', 'playerId'=>$player->id, 'pageId'=>$page->id, 'bool'=>'FALSE'))); ?>
</div>
Upvotes: 0
Views: 952
Reputation: 3559
$toggle = $model->is_favourite? "false": "true";
$actionUrl = Yii::app()->createUrl('user/favoritePage', array(
'playerId'=>$player->id, 'pageId'=>$page->id
));
//render input type=submit with id=favourite-button
echo CHtml::ajaxSubmitButton(
($model->is_favourite? 'Favourite' : 'Un-Favourite'), //label button
$actionUrl,
array(
'data' => 'js:{bool: $("#favourite-button").attr("toggle")}', //get current status of button (favourite or not) as param to post
'success'=>'js:function(data){
//ajax success, update label and status of button for next time
data = $.parseJSON(data);
$("#favourite-button").val(data["label"]);
$("#favourite-button").attr("toggle", data["toggle"]);
}'
),
array(
'id' => 'favourite-button', // set id for button
'toggle' => $toggle // set attribute to hold favourite status, or you can set it on hidden field instead and then update the selector on ajax success
)
);
On controller User
public function actionfavoritePage(){
if( Yii::app()->request->isAjaxRequest(){ // this check is not necessary if you write this function just for ajax call only
$playerId- = $_GET['playerId']; // get query string
$pageId- = $_GET['pageId']; // get query string
$bool = $_POST['bool']; // get status true OR false
//do your stuff to save status here
...
//then return result as json
echo json_encode(array('label' => '[your new button label]', 'toggle'=>$bool?'false':'true'));
exit();
})
}
Upvotes: 1
Reputation: 975
You'll want to use CHtml::ajaxButton()
: http://www.yiiframework.com/doc/api/1.1/CHtml#ajaxButton-detail
Here's a tutorial on how to use it: http://www.yiiframework.com/wiki/49/update-content-in-ajax-with-renderpartial/
If you want the title of your button to change, place a condition in a view, and make sure your button is returned in the ajax result.
Upvotes: 1