Zend Framework 2 AJAX: return JSON response from controller action. The proper way.

There is a lot of solutions over the web on how to return data on AJAX request in your Zend Framework 2 application. But none of them seems to be aware of the "right way" described in Zend Framework 2 manual - http://framework.zend.com/manual/2.0/en/modules/zend.mvc.examples.html#returning-early

Implementation example:

<?php

namespace <YOUR_MODULE>\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Json\Json;

class AjaxController extends AbstractActionController
{

    public function testAction()
    {
        $data = array(
            'result' => true,
            'data' => array()
        )
        return $this->getResponse()->setContent(Json::encode($data));
    }
    
}

Comments

  1. Header ouput is html:

    Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

    ReplyDelete
  2. This is the kinda article I like. Short as hell, but gets the job done :) call me lazy, don't care, it was good ;)

    ReplyDelete
  3. Happy to share your blog! Good article! I love it

    ReplyDelete
  4. This way the header is not automatically set, is there a better way?

    ReplyDelete
  5. change the content type like this:

    $this->getResponse()->getHeaders()->addHeaders(array('Content-Type'=>'application/json;charset=UTF-8'));
    return $this->getResponse()->setContent(Json::encode($ata));

    ReplyDelete
  6. Its good work , is it the perfect way ..?

    ReplyDelete

Post a Comment

Popular posts from this blog

Memory efficient array permutation in PHP 5.5 using generators

How to dump http request headers with PHP under CGI/FastCGI SAPI

Jqgrid show totals in the footer plugin