Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return json to ajax in symfony?

Tags:

symfony1

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.

like image 276
never_had_a_name Avatar asked Jun 01 '10 20:06

never_had_a_name


2 Answers

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));
like image 198
Tom Avatar answered Oct 11 '22 17:10

Tom


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.

like image 28
timdev Avatar answered Oct 11 '22 15:10

timdev