juanmi
juanmi

Reputation: 147

Yii controller method call from view button

I've been reading a lot about this but I can't find a proper solution for my issue.

In Yii framework, I need to execute a controller method after clicking into a button from a view. I tried to do this with Javascript but it's not working. I don't need to change anything from the view, just execute the code into the controller. Just after controllers execution is done, I have to get the return variable to show some answer on the view.

Upvotes: 0

Views: 2406

Answers (3)

juanmi
juanmi

Reputation: 147

Finally I got a solution making a mixture of your advices. Besides, I'm working on a third party project and the code is quite confusing, actually the controller wasn't in the right directory... Anyway, this is my solution:

On my view, call to my JavaScript function

onclick="myMethod(myVar");

then:

<script>
function myMethod(Var) {

$.ajax({
    type: "POST",
    url:    "<? echo Yii::app()->createUrl('MyController/MyControllerMethod'); ?>",
    data:  {val: Var},
    success: function(msg){
        alert("Operation result: " + msg)
    },
    error: function(xhr){
        alert("failure"+xhr.readyState+this.url)
    }
});
}
</script>

In my controller, just did some operations and return with echo:

public function actionMyControllerMethod() {

   // some operations

   echo $result;
}

Upvotes: 0

Igor Savinkin
Igor Savinkin

Reputation: 6277

AjaxButton in yii:

echo CHtml::ajaxButton('ButtonName',Yii::app()->createUrl('controller/action'),
                array(
                    'type'=>'POST',
                    'data'=> 'js:{"data1": val1, "data2": val2 }',                        
                    'success'=>'js:function(data){ alert(data); /* */}',
                    'update'=>'selectorNameToBeUpdated',           
                ),array('class'=>'someClass',));

Upvotes: 2

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12401

     onclick="callController();"

Use it using ajax, create a function and call it via javascript using onclick event.

 <script>
  function callController(){
   $.post("index.php?r=controllerName/functionName, function (data) {
  });

 }
 </script>

Upvotes: 1

Related Questions