0

So I am trying to create an Android mobile application and I am using CakePHP as my serverside. I will not be needing any HTML views, I will only be responding with JSON objects.

I have taken a look at http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent and with that I've created this:

class LocationsController extends AppController
{
    public $helpers = array('Html', 'Form');
    public $components = array('RequestHandler');
    function index()
    {
        $locations = $this->Location->getNearest();
        $this->set(compact('locations'));
        $this->set('_serialize', array('locations'));
    }
}

and I have added this to my routes.php:

Router::mapResources('locations');
Router::parseExtensions('json');

Nothing is displayed when I run this apart from the default CakePHP layout style. If I remove the index.ctp view file, I get an error that it can't find the view file. Why does it still require a view file? I thought with the serialize approach it does not need a view. I have tried looking in the Google Chrome developer console and there is no response that contains the JSON object. However, the MySQL has performed perfectly fine.

Johnathan Au
  • 5,244
  • 18
  • 70
  • 128

2 Answers2

0

Put $this->render(false); between

public $components = array('RequestHandler');

and

function index()

Now it doesn't require an index.ctp file anymore.

See this link for more information.

JorickL
  • 165
  • 10
  • Error: syntax error, unexpected '$this' (T_VARIABLE), expecting function (T_FUNCTION). Either way, this will just obliterate all output in the browser. I won't be able to test or see my JSON data if I use render(false). – Johnathan Au Mar 02 '13 at 19:35
  • 1
    Oh, darn. Yeah, you are right. I suspected that would've done the job, but this is with JSON data. Then I'm not able to help you, sorry. – JorickL Mar 02 '13 at 19:41
  • Thanks nevertheless =). I used public $viewClass = 'Json'; and it seems to have done the trick on the browser end. I haven't tested it on the Android end though. I'm just worried about how Android will receive the data. I don't want it to receive any html, css or javascript content. – Johnathan Au Mar 02 '13 at 19:48
0

I just did the same thing, using the REST API, as I want the response in the JSON. What I did is I used the Chrome advanced rest client. In that I made a request to my localhost server by using the appropriate GET method, and it succeeded.

like: GET /users/view/103.json

you will get the response as:

{"users":{"User":{"id":"103","username":"abc","password":"xyz",
 "email-id":"abc@xyz.com"}}} 
pb2q
  • 58,613
  • 19
  • 146
  • 147
pranav
  • 1