tags:

views:

305

answers:

2

in symfony i call an action and i want this to return json to jquery frontend.

the jobeet tutorial teaches how to return a partial but i want to return json, not a partial.

thanks.

+1  A: 

The cheap way:

function executeSomethingThatReturnsJson(){
  $M = new Model();
  $stuff = $M->getStuff();
  echo json_encode($stuff);
  die(); //don't do any view stuff
}

The smarter way:

A smarter way is to create a nice subclass of sfActions that helps handling json-stuff.

In a project I did recently, I created a application called 'api' (./symfony generate:application api)

and then created a file like:

api/lib/apiActions.class.php

<?PHP
class apiActions extends sfActions {
  public function returnJson($data){
    $this->data = $data;
    if (sfConfig::get('sf_environment') == 'dev' && !$this->getRequest()->isXmlHttpRequest()){
      $this->setLayout('json_debug'); 
      $this->setTemplate('json_debug','main');
    }else{
      $this->getResponse()->setHttpHeader('Content-type','application/json');
      $this->setLayout('json');
      $this->setTemplate('json','main');
    }
  } 
}

Notice that I explicitly set the template there.

So my jsonSuccess.php template is simply:

<?PHP echo json_encode($data);

While json_debugSuccess.php makes things prettier:

<?PHP var_dump($data); ?>

Then you can have a controller that extends apiActions (instead of the usual sfActions) that looks like this:

<?php
class myActions extends apiAction {
  public function executeList(sfWebRequest $request)
  {
    $params = array();
    if ($request->hasParameter('id')){
      $id = $request->getParameter('id');
      if (is_numeric($id)){
        $params['id'] = $id;
      }
    }
    $data = Doctrine::getTable('SomeTable')->findAll();
    $this->returnJson($data);
  }
}

Disclaimer: The code above is copy/pasted out of an app I have, but simplified. It's for illustrative purposes only -- but it should get you heading in the right direction.

timdev
this was really funny :) u posted a lot of codes but the previous answer was one line and it worked :) 1+ for u being eager to help though!:)
never_had_a_name
Right -- that other answer is a nicer version of "the cheap way". The rest of my answer is about handling things differently based on environment, though I'm sure it could be done a lot cleaner.
timdev
+4  A: 

If it's just a normal AJAX action you're returning it from, I think I've used the following somewhere in the past:

return $this->renderText(json_encode($something));
Tom