Search code examples
ajaxzend-frameworkfunctioncallcontroller-action

Zend Framework: How to call a Function (not a Controller Action) using ajax?


Assume that I have a public function in IndexController called test():

public function test(){
    //some code here
}

In index.phtml view file, I want to use JQUERY AJAX to call test() function but have no idea about this.

Code:

<a href="javascript:void(0)" onclick="callTestFunction()">Click me to call test() function()</a>
<script>
callTestFunction = function(){
    $.ajax({
        type: "POST",
        Url: ***//WHAT SHOULD BE HERE***
        Success: function(result){
            alert('Success');
        }
    });
}
</script>

Solution

  • I would suggest writing an action for it. If there is logic inside of test() that you need other actions to be able to use, the factor that out.

    There are a couple of reasons for having it be its own action:

    • You can test the results of the action directly instead of having to go through a proxy.
    • You can take advantage of context switching depending on if you need JSON returned or HTML
    • It is an action that you are trying to hit via AJAX, so there's no need to hide it.

    Remember that not every action has to be its own full fledged page. One thing to make sure you do is disabling the auto-rendering of the view inside this action so it doesn't complain about not being able to find it.