views:

3411

answers:

3
A: 

Check out the cakePHP book on Request Handling:

http://book.cakephp.org/view/174/Request-Handling

CakePHP has some built in functionality to handle controller methods that return json.

PetersenDidIt
+1  A: 

First, to answer your question, yes you can do without a view (and this is a good case for doing so). In your controller action (test, in this case), just set $this->autoRender = false;. That's what I usually do and just echo out the encoded JSON string in the controller itself. Less clutter that way.

The next thing that I'd look at are your debug settings in config.php. If not set to 0, there's a very good chance that this is your problem. Your echo statement may be echoing the JSON-formatted string, but appending debug output to it. In the method, just include Configure::write ( 'debug', 0 ). This will disable debug only for the current request. I usually do this in my AppController actually:

if ( $this->RequestHandler->isAjax() ) {
   Configure::write ( 'debug', 0 );
}

I'd engage a tool like Firebug and see what's happening to your ajax request. It will monitor those requests and provide the request and response headers for you to inspect. That may help. If the latter is the problem, then Firebug would have shown you that in the response headers.

Rob Wilkerson
A: 

I agree with Rob, except with setting your debug in the app controller. It gets a little annoying to me because you have to set the debug level in the app controller every time you want to debug something for a specific function. I write my handler out like this in the controller i am working in.

Configure::write('debug', 0);
$this->autoRender = false;

Also I agree with the use of firebug. With firebug all you have to do is open firebug, click on console, and then run your test. This will tell you what you are doing with your jquery and give you the results.

Stirling