Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email: hello@sanisoft.com

Blog

[CakePHP] Sending JSON data in response to a controller action


In my last post we saw a very simple trick to set javascript variables from controller action so that they are available in the javascript files. On the same lines a very common requirement is sending JSON data as output of the controller action. This is mainly required for those actions which are called by AJAX request.

Many of us (including me) will be doing something like this in our controller action

And in view ( views/controller_name/my_action.ctp)

The above logic is absolutely fine and there are no issues with it. However, if you have a number of controller actions (across different controllers) which output the JSON data then you would be repeating the code in all your views. We should be coming up with a better solution and implement something which is reusable.

Here is how to do it…

Add a new method in your app_controller.php called as sendJson().

Create a new element views/elements/json.ctp

And lastly modify your controller action to use AppController::sendJson() method.

You can safely remove the action specific view i.e. views/controller_name/my_action.ctp as it won’t be used any longer.

So in short, AppController::sendJson() can be used in any controller action to send the response as JSON.

About the Author

Abbas Ali is a Mechanical Engineer by education. He turned to programming and took it as a profession just after finishing his studies. He is fascinated equally by both machines and computers. He leads the team of dynamic programmers at SANIsoft and works as a Technology Manager. He is also an active developer on the Coppermine Picture Gallery team.

6 comments

  1. Pingback: Tweets that mention [CakePHP] Sending JSON data in response to a controller action at SANIsoft – PHP for E Biz -- Topsy.com

  2. 1) You should read about RequestHandler->respondAs
    2) You dont need elements and stuff. Just set autoRender in AppController to false for ajax requests and in your action
    echo json_encode($response).

  3. Pingback: PHP Answers » Answers Archive » Re: Using render() with Ajax (Cake 1.3.8)

  4. Pingback: jquery - CakePHP - Come restituire la stringa (come JSON) dal controller azione richiesta Ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.