bordeux
bordeux

Reputation: 622

Ajax with Zend - JSON and ViewModel in one

I want replace output in zend2, from html to fullJSON with response status and others data.

For example: when i enter by browser /mycontroller/action sholud show layout with view

when i enter /mycontroller/action/?ajax should show JSON array with vars from ViewModel, with response status and headers .

How can i do this with zend2? I want do it on every controler in my module

class MyController extends AbstractActionController
{
    public function indexAction()
    {
        return array("test"=>"test2")
    }   
    public function redirectAction()
    {
        $this->redirect()->toUrl('http://google.pl');
        return array("test"=>"test5")
    }

}
/*
when i eneter
/MyController/index should display normal layout with html
/MyController/index?ajax should display 
{
    response: 200,
    headers: {} - response headers
    data: {
        "test" => "test2"
    }
}

when i eneter
/MyController/redirect should redirect me to other place
/MyController/redirect?ajax should display 
{
    response: 302,
    headers: {
        'redirect' => 'http://google.pl'
    } - response headers
    data: {
        "test" => "test5"
    }
}
*/

Upvotes: 0

Views: 415

Answers (2)

texdc
texdc

Reputation: 53

ZF will handle output negotiation automatically, but if you'd like to handle it manually, here's one way:

namespace My\Module;

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

class MyController extends AbstractActionController
{
    public function indexAction()
    {
        $stuff = array("test" => "foo");
        if ($this->getRequest()->isXmlHttpRequest()) {
            return Model\JsonModel($stuff);
        } else {
            return Model\ViewModel($stuff);
        }
    }
}

Another way is to register an event listener on an MVC event: dispatch, finish or render.

Upvotes: 0

STLMikey
STLMikey

Reputation: 1210

This is how I accomplish this:

$headers = $request->getHeaders();
$requested_with_header = $headers->get('X-Requested-With');
if($requested_with_header->getFieldValue() == 'XMLHttpRequest') {
     return new Zend\View\Model\JsonModel($data);
}
else{
    return new Zend\View\Model\ViewModel($data);
}

Upvotes: 2

Related Questions