Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework JSON Output

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.

like image 809
Alex Pliutau Avatar asked Sep 15 '10 08:09

Alex Pliutau


4 Answers

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'
));
?>
like image 84
dchusovitin Avatar answered Nov 04 '22 11:11

dchusovitin


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'];

like image 43
shereifhawary Avatar answered Nov 04 '22 12:11

shereifhawary


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.

like image 27
Piotr Pankowski Avatar answered Nov 04 '22 12:11

Piotr Pankowski


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)
  );
like image 1
Vaidas Zilionis Avatar answered Nov 04 '22 12:11

Vaidas Zilionis