rockstardev
rockstardev

Reputation: 13527

Connecting a YII ajaxButton to a controller to execute server side functions?

I have the following button:

<?php $this->widget('bootstrap.widgets.TbButton', array(
  'label'=>'myLabel',
  'buttonType'=>'ajaxButton', 
  'url'=>'someUrl', 
  'type'=>'primary', // null, 'primary', 'info', 'success', 'warning', 'danger' or 'inverse'
  'size'=>'small', // null, 'large', 'small' or 'mini'
  'ajaxOptions'=>array(
      'type' => 'POST',
      'beforeSend' => '
        function( request ) {
          //alert(request);
        }'
      ,
      'success' => 'function( data ) {
          //alert(data);
        }'
      ,
      'data' => array( 
        'actionName' => "INCREMENT"
      )
  ),
)); ?>

So, the tricky part is, how do I connect this button to actual backend code? I would assume it's done by posting to a URL. In my case I've got a URL set as:

'url'=>'someUrl'

Does this mean I must create a view, controller and model so there is a URL to post to? isn't there an easier way without going through that effort?

Upvotes: 1

Views: 2255

Answers (1)

bool.dev
bool.dev

Reputation: 17478

You do not necessarily need a new view. But you will need an action that catches this request.

In Yii each action has a unique url that refers to it, and there are functions that generate such a url for us, namely createUrl. There are other versions of createUrl also, the one here is from CController.

So you'd modify your url property as:

'url'=>$this->createUrl('controller-name/action-name')

Then in your controller add the action:

public function actionActionname(){
    // do your server-side stuff
    // maybe also return some message back to client-side view
    if(success)
        echo "Y";
    else echo "N";
    Yii::app()->end();
}

Upvotes: 1

Related Questions