CJSON::encode() and return statement

Hello, I want to return json response on request, and I found the interesting issue, when I do this:

return CJSON::encode($data);

, it does not return anything, but when do this:

echo CJSON::encode($data);

, all works fine. Why I cant use return statement?

Why you do believe that can’t you?

Let’s start with documentation.

As you can see, [size="2"][font="Courier New"]CJSON::encode($data)[/font] [/size][size="2"]returns JSON string as result. [/size]

[size="2"]In the first case [/size][size="2"]([/size][size="2"][font="Courier New"]return CJSON::encode($data);[/font][/size][size="2"]), you are trying to return a result of the encode method in the controller. In order to send it as response, you could do something like this: [/size]

[font="Courier New"]$jsonString=CJSON::encode($data);//Assign result of the encode function to the $jsonString variable

echo $jsonString;//echo jsonString variable

Yii::app()->end();//End controller action[/font]

[size="2"]In the second case ([/size][size="2"][font="Courier New"]echo CJSON::encode($data);[/font][/size][size="2"]), you are printing the result of the encode method inside the controller, and that is response that client will receive. After [/size][size="2"][font="Courier New"]echo[/font] [font="Courier New"]CJSON::encode($data);[/font] you should add the following line [font="Courier New"]Yii::app()->end();[/font][/size]