Pla558 Pla558 - 11 days ago 7
Ajax Question

CakePHP 3 View to Variable

my question is give it a way to parse a view file (.ctp) into a variable ?
I want to create a ajax function that gives a ctp file or better says the content of this back.
The call from the javascript to cakephp's controller work but now i doesnt now how i can get my specified ctp file in the template folder parse it into a variable and send it back to the javascript function.

Answer

Lets say, you are using the controller sites and the view is index.

app/Controller/SitesController.php:

public function index() {
    if($this->request->is('ajax') {
        // prepare output for ajax. best way to do is to prevent styled output
        $this->render('TestView/index');
    }
}

In your TestView/index.ctp you can now prepare your output for ajax and just call the controller/action URL by AJAX:

$.ajax({
    url: "/sites/index",
    success: function(reponse) {
        console.log(response); // here comes the output from /sites/index
    }
});