How to return only JSON from Zend - php

I'm using Zend Framework 1.x for my project. I want to create a Web service return only JSON string for the caller function. I tried to use Zend_Controller_Action and applied those ways:
1.
$this->getResponse()
->setHeader('Content-type', 'text/plain')
->setBody(json_encode($arrResult));
2.
$this->_helper->getHelper('contextSwitch')
->addActionContext('nctpaymenthandler', 'json')
->initContext();
3.
header('Content-type: application/json');
4.
$this->_response->setHeader('Content-type', 'application/json');
5.
echo Zend_Json::encode($arrResult);
exit;
6.
return json_encode($arrResult);
7.
$this->view->_response = $arrResult;
But when I used cURL to get result, it returned with JSON string surrounded by some HTML tags. Then I tried to user Zend_Rest_Controller with the options above. It still did not success.
P.S.: Most of those ways above are from the question which had been asked on Stack Overflow.

I Like this way!
//encode your data into JSON and send the response
$this->_helper->json($myArrayofData);
//nothing else will get executed after the line above

You need to disable the layout and view rendering.
Explicit disable layout and view renderer:
public function getJsonResponseAction()
{
$this->getHelper('Layout')
->disableLayout();
$this->getHelper('ViewRenderer')
->setNoRender();
$this->getResponse()
->setHeader('Content-Type', 'application/json');
// should the content type should be UTF-8?
// $this->getResponse()
// ->setHeader('Content-Type', 'application/json; charset=UTF-8');
// ECHO JSON HERE
return;
}
If your using the json controller action helper you need to add a json context to the action. In this case the json helper will disable the layout and view renderer for you.
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('getJsonResponse', array('json'))
->initContext();
}
public function getJsonResponseAction()
{
$jsonData = ''; // your json response
return $this->_helper->json->sendJson($jsonData);
}

Your code would need to disable the layout as well in order to stop the content being wrapped with the standard page template. But a much easier approach would just be:
$this->getHelper('json')->sendJson($arrResult);
the JSON helper will encode your variable as JSON, set the appropriate headers and disable the layout and view script for you.

It is much easier.
public function init()
{
parent::init();
$this->_helper->contextSwitch()
->addActionContext('foo', 'json')
->initContext('json');
}
public function fooAction()
{
$this->view->foo = 'bar';
}

Related

Yii, Is it good MVC practice to echo in the controller?

It seems like i am not following the MVC design structure.
I'm making an ajax call from my view to a Controller function
Controller
public function actionGetClient()
{
$user = Client::model()->findByAttributes(array('email'=>$_POST['email'], 'password'=>$_POST['pass']));
echo $user->fullname;
}
View (the calling ajax)
CHtml::ajaxLink(
$text = 'get user',
$url = Yii::app()->createUrl('[my controller]/getClient'),
$ajax=array (
'type'=>'POST',
'data' => array('email'=>email, 'pass'=>pass),
'beforeSend' => "function( request )
{
$(\".result\").html(\"fetching...\")
}",
'success'=>"function(data){
$(\".result\").html(\"user is :\"+data)
}
"
));
Is it good to "echo" the $user->fullname inside the controller for the ajax success function to display it? My boss doesn't like it when i print stuff in my controller, how can i approach this
because when i use return instead, the ajax success gets a null value
return $user->fullname;
No,
It's not a good practice.
You need to create a view to use echo.
You can use return $this->renderPartial('VIEW_NAME'); to render a view without Layout.
You should write 'return' instead of 'echo'. 'echo' is not a good practice for ajax response. You don't need to make a new view for just return a name in your case.
public function actionGetClient()
{
$user = Client::model()->findByAttributes(array('email'=>$_POST['email'],'password'=>$_POST['pass']));
return $user->fullname;
}
No. A controller’s supposed to pass its results to a view for rendering.
I would avoid echoing in the controller what we usually do is have a ajax view folder and a json view and render with that so:
public function actionGetClient()
{
$user = Client::model()->findByAttributes(array(
'email'=>$_POST['email'],
'password'=>$_POST['pass']
));
$this->render("json",array("outputData"=>$user));
}
then add this to the controller as well:
public function getViewPath(){
if(Yii::app()->request->isAjaxRequest){
if(($module=$this->getModule())===null)
$module=Yii::app();
return $module->getViewPath().DIRECTORY_SEPARATOR."ajax";
}
return parent::getViewPath();
}
and in the ajax views folder add a json.php file like so
header('Content-Type: application/json');
// output data
echo json_encode($outputData);
please degug the code as I wrote it free hand. You can also set a marker in the controller like $viewPath and set it before the rendering

CakePHP - JsonView rendering is sub function of the controller

I'm using Cakephp with json parse extension and the RequestHandler component in order to create Web services using json.
I created a controller named Ws
In this controller I have a named userSubscribe
In order to avoid a lot of If else statements in the next methods, I thought about using a private function inside this controller that will check somes conditions and stop the script normaly BUT ALSO render the json normaly. I just want to do a DRY way !
My question is :
How could I render the json view in a sub function (called by the userSubscribe) ?
To make it clear, here is the style code that would like
public function userSubscribe() {
$this->check();
// Following code only executed if check didn't render the json view
// $data = ...
$code = 1;
$i = 2;
}
private function check() {
$input = &$this->request->data;
if ($_SERVER["CONTENT_TYPE"] != "application/json") { // For example
$result = "KO";
$this->set(compact("result"));
$this->set('_serialize', 'result');
$this->render(); // HERE, it will stop the 'normal behaviour' and render the json with _serialize
}
if (!isset($input["input"])) {
$result = "KO";
$this->set(compact("result"));
$this->set('_serialize', 'result');
$this->render(); // HERE, it will stop the 'normal behaviour' and render the json with _serialize
}
}
It's seems to be quite simple to do, but why can't I find the answer ?!
Thanks in advance for clue/advise/anything !

Laravel JavaScript File response for JSONP response

I'd like to generate a JavaScript file for JSONP data exchange.
All fine, but I need / want to set the header as :
header("Content-Type: text/javascript");
or
header("Content-Type: application/javascript");
Is this possible in a response from a controller in Laravel 4, or do I need to create a view and set the header with PHP?
I'd like to output something like:
var obj = JSON.parse('{"item1":"value1","item2":"value2"}');
// then do whatever with the object
$('#somediv').html(obj.item1);
Thanks for your help in advance
Okay, looks like I have to answer my question myself :-). Thanks to #terrylow for trying though.
Here is the way to change the header of my response using my function in my controller
public function javascriptResponse(){
$statusCode = 200;
$content = "var obj = JSON.parse('{\"item1\":\"value1\",\"item2\":\"value2\",\"some\":\"whoaevaNew\"}');";
$response = Response::make($content, $statusCode);
$response->header('Content-Type', 'application/javascript');
return $response;
}
variable content can also be filled with a view:
$content = View::make('tools/jsonp_resonse'); // also possible with view
Hope that will help someone...
you can use this method provided by laravel
return Response::jsonp($callback, $data,$status, $header);

Telling cakePHP to render as XML / use xml/blah.ctp instead of blah.ctp

I have been successfully using XML view files in CakePHP (request the XML output type in headers so CakePHP will use e.g. Orders/xml/create.ctp instead of Order/create.ctp).
However, now i need to add some functionality that requires me to the reformat the XML at the end of most business logic in the controller.
So i tried this in the controller action:
public function createorder() {
$this->autoRender = false; // disable automatic content output
$view = new View($this, false); // setup a new view
{ ... all kinds of controller logic ...}
{ ... usually i would be done here and the XML would be outputted, but the autorender will stop that from happening ... }
{ ... now i want the XML in a string so i can manipulate the xml ... }
$view_output = $view->render('createorder'); // something like this
}
But what this gives me is:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<error>View file &quot;/Users/test/Documents/hosts/mycakeapp/app/View/Orders/createorder.ctp&quot; is missing.</error>
<name>MissingViewException</name>
<code>500</code>
<url>/orders/createorder/</url>
</response>
So i need to tell CakePHP to pickup the xml/createorder.ctp instead of createorder.ctp. How do i do this?
Cheers!
This answers refers to cakephp 2.4
I have been successfully using XML view files in CakePHP (request the XML output
type in headers so CakePHP will use e.g. Orders/xml/create.ctp
instead of Order/create.ctp).
In lib/Cake/View you can see different View files like:
View.php
XmlView.php //This extends View.php
JsonView.php //This extends View.php
So you told cakephp to use the XmlView. When you create a new View you need to use the XmlView instead of View. Or you can create your own custom View and put it inside app/View folder. In your custom View you can set your subdir.
<?php
App::uses('View', 'View');
class CustomView extends View {
public $subDir = 'xml';
public function __construct(Controller $controller = null) {
parent::__construct($controller);
}
public function render($view = null, $layout = null) {
return parent::render($view, $layout);
}
}
So what you need now is to create your custom view $view = new CustomView($this, false);
You can also write in your CustomView functions to handle the data as xml and use it to every action.
Also #Jelle Keizer answer should work. $this->render('/xml/createorder'); points to app/View/xml/createorder. If you need this to point to app/View/Order/xml/create just use $this->render('/Orders/xml/create');.
$this->render('/xml/createorder');

How to Test cakephp parseExtension?

I setup the parseExtension for json in my cakephp 2.3.0. No errors are display. It works?
How can I test is?
In RoR ist ist very easy to test via
https://mydomain.de/view/4.json
How does it run on cakephp?
My View-Action is this.
public function view($id = null) {
if (!$this->Atla->exists($id)) {
throw new NotFoundException(__('Invalid atla'));
}
$options = array('conditions' => array('Atla.' . $this->Atla->primaryKey => $id));
$this->set('atla', $this->Atla->find('first', $options));
$this->Atla->id = $id;
$result = $this->Atla->read();
$this->response->type('json');
$this->response->body(json_encode($result));
return $this->response;
$this->set(compact('atlas'));
}
Why i always get an json-request?
If you use the _serialize key cakephp can automatically create json and xml views for you. I typically use the following to create json or xml views:
public function view() {
// data I want to display
$record1 = $this->ModelName->find('first', ...);
$this->set('record1', $record1);
$record2 = $this->ModelName->find('first', ...);
$this->set('record2', $record2);
// option 1: serialize the hard way
$this->set('_serialize', array('record1', 'record2'));
// option 2: serialize the easy way
$this->set('_serialize', array_keys($this->viewVars));
}
PS: the code after your return statement will never be executed.
you'll have create the view
app/View/Atlas/json/view.ctp
which is the view that is being used for .json requests.
Requests without .json will use the regular view file:
app/View/Atlas/view.ctp
There's more information on creating/using JSON and XML views here:
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#using-a-data-view-with-view-files
From that page the view.ctp may contain something like;
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));
However, it really depends on what you're trying to achieve. If you will only use the 'Atlas/view' action for JSON responses, and won't be using HTML at all, sometimes you can get away with generating the response-body inside your Controller. Not very much 'in line' with MVC conventions, but it saves you from creating a view that does nothing more than echo json_encode($data); ;)
public function view($id)
{
$this->MyModel->id = $id;
$result = $this->MyModel->read();
$this->response->type('json');
$this->response->body(json_encode($result));
//Return reponse object to prevent controller from trying to render a view
return $this->response;
}
If you do want to use both 'HTML' and 'JSON', depending on the request (with/without .json extension), you should have two view files; 1 for JSON and 1 for HTML;
// This view will be used for your JSON requests
app/View/Atlas/json/view.ctp
// This view will be used for non-JSON (html) requests:
app/View/Atlas/view.ctp
In the json-view, output the data using json_encode(.....);
In the 'normal'/html view, just output normal data
In your controller, set the data as normal
public function view($id = null) {
$this->Atla->id = $id;
if (!$this->Atla->exists()) {
throw new NotFoundException(__('Invalid atla'));
}
$this->set('atla', $this->Atla->read());
}

Categories