Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2: Return JSON only for Ajax Call

I'm trying to learn ZF2. I have a page that uses Ajax to get some data. The ZF2 function should return an JSON string.

<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;

class DocumentsController extends AbstractActionController {

    public function indexAction() {

    }

    public function getTreeDataAction() {
        $json = new JsonModel(array(
                    'title' => 'Some Title'
                ));
        return $json;
    }

}

But I keep getting this Fatal Error:

( ! ) Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "application/documents/get-tree-data"; resolver could not resolve to a file' in ../vendor/ZF2/library/Zend/View/Renderer/PhpRenderer.php on line 451

I have been searching around for this error and the best way to make ajax calls in ZF2, however results for ZF1 or ZF2 betas keep coming up and do not work. Thank you for any advice you can give.

like image 436
Gregory Burns Avatar asked Dec 05 '22 14:12

Gregory Burns


1 Answers

Hmm, that error pretty much implies that it tries to access the default rendering strategy, which is quite weird... Have you added the JsonStrategy to your view_manager?

//module.config.php
return array(
    'view_manager' => array(
        'strategies' => array(
           'ViewJsonStrategy',
        ),
    ),
)

Furthermore it's a good idea to set the correct accept header for within you ajax calls to only accept application/json content type. With this set, it should actually work. Out of curiousity though, does modules/__NAMESPACE__/view/__namespace__/documents/get-tree-data.phtml exist?

like image 111
Sam Avatar answered Dec 07 '22 22:12

Sam