views:

113

answers:

4

In controller I am generating a special form by ID, passed from AJAX. Form output is JSON. Form creates finely. But my problem is to show this JSON in view. How?

Thank you.

+1  A: 

The easiest way is to stop view from being executed:

function jsonAction () {
    ....
    print $json;
    exit;
}

Also see check http://pl.php.net/json_encode if you don't have JSON string already.

Piotr Pankowski
+2  A: 

json is a encoded string containing vars in js style if you need to access the member in this string you need to json_decode the string so

$result = json_decode($jsonString);

but note that json treat php associative array like php object ... so if you pass an array you can access it as $result->memberReference not $result['memberReference'];

S.Hawary
+2  A: 

In controller (http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.json):

$this->getHelper('json')->sendJson(array(
    'param1' => 'v1'
    'param2' => 'v2'
));

In view (http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.json):

<?php
echo $this->json(array(
    'param1' => 'v1'
    'param2' => 'v2'
));
?>
dchusovitin
+1  A: 

You can use Zend class

$sData = Zend_Json::encode($aArray);

Or you can use advanced scenario like:

$data = array(
  'onClick' => new Zend_Json_Expr('function() {'
   . 'alert("I am a valid javascript callback '
   . 'created by Zend_Json"); }'),
 'other' => 'no expression',
);

$jsonObjectWithExpression = Zend_Json::encode($data,false,
     array('enableJsonExprFinder' => true)
  );
Vaidas Zilionis
It useful if you using AJAX which gets json encoded new data with objects :)
Vaidas Zilionis