Ajax, ZF2 action and json return

by Iva Korlevic
November 12, 2014

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! 🙂

Comments

0 thoughts on “Ajax, ZF2 action and json return”

Tell us your opinion:

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