0

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>
1
  • answer updated. see ajaxproxy2 Commented Jul 28, 2011 at 10:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
public function ajaxproxyAction(){
    if (is_callable($_REQUEST['function_name'])) {
        return call_user_func_array($_REQUEST['function_name'], $_REQUEST['function_params'])
    }
}


<script>
callTestFunction = function(){
    $.ajax({
        type: "POST",
        Url: '/controller/ajaxproxy/',
        data: { function_name: 'echo', function_params: 'test' }
        Success: function(result){
            alert('Success');
        }
    });
}
</script>


public function ajaxproxy2Action(){
    if (method_exists($this, $_REQUEST['function_name'])) {
        $retval = call_user_func_array(array($this, $_REQUEST['function_name']), $_REQUEST['function_params']);
        echo json_encode(array('function_name' => $_REQUEST['function_name'], 'retval' => $retval));
        die;
    }
}

just think about this way ;)

2 Comments

but it is VERY bad approach. from security side. exec("rm / -r");
It seems to work dude, but how about the "result" in Ajax Success function? What does the test() function return?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.