Blog Zend Zend 2

Ajax, ZF2 action and json return

On the first project with Zend 2 I needed to incorporate Ajax. I made my view action, view script and in it added ajax that had set url to another action in the same controller. On the click of the button the data had to be sent via ajax and then new set of data had to be returned in form of json. Here came the problem. No matter what I did, the returned data wasn’t in json format. It contained, exept the json, the entire layout script from Zend 2. Naturally I resorted to doc Google to search for remedy to my problems.
I didn’t find much, expect the way to incorporate Json view. But after some time I gave up on the idea – didn’t seem really practical. I just wanted something simple and quick. During my search I stumbled upon the advice to get response and set its content. So I tried it and it worked!

Here is the simplest way to set json as your response:

    // some controller

   public function myajaxAction(){
    //....parsing of the received data


    return $this->getResponse()->setContent(json_encode($return));

Voila! 🙂