cakephp Ajax request handling Basic CakePHP 2.x example


Example

Controller: In the Controller you have to add the RequestHandler component. This Enables CakePHP to automatically detect Ajax requests(see: http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html for more info):

class YourController extends AppController {
    public $components = array('RequestHandler');
    //...

    public function ajaxCall() {
        if($this->request->is('ajax'){
            // some code that should be executed
            // ...
            // variables you want to return
            $this->set(compact('firstVariable', 'secondVariable'));
            $this->set('_serialize', array('firstVariable', secondVariable))
    }
}

View Code (using jQuery):

<script>
$.ajax({
    type: 'POST',
    url: '/yourController/ajaxCall',
    success: function (result) {
        // result is a JSON array of the returned Variables
    },
    error: function (result){
        console.log(result);
    }
});
</script>