Ajax, ZF2 action and json return

Hi!
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=$object->fetchData();

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

Voila! 🙂

Published by Iva Korlevic

I'm a web programmer that started working with web pages in 2008 by programming simple HTML/CSS webpages. I finished Faculty of electrical engineering in April 2010 and started working in Inchoo in May 2010. During the time in Inchoo I worked on Zend applications, Magento stores and a few Wordpress projects. I left Inchoo in January 2012 and worked for a couple of months in Gauss Informatika as Zend teacher and team leader. In May 2012 I left Gauss Informatika and joined the team at NTH Media. For next 6 months I worked on various mobile and Wordpress projects. In the February 2013 together with MArin Blazevic I opened Proodos. I'm still continuing my work as Zend and Magento programmer. In summer 2015 I also started to work for Webbite Media GMBH and on 19th August 2015 I passed Magento Certification Exam and am now Magento Certified Developer.

Leave a comment

Your email address will not be published. Required fields are marked *