This is the template I use in CakePHP 1.3.x. Usually this process:
- Create alternative json-oriented layouts and view files
- Detecting if an incoming AJAX request
- Explicit display of alternative json layout / view instead of text / html
Be sure to include the RequestHandler and JsHelper component in the application controller.
In this controller:
function test() { if($this->RequestHandler->isAjax()) { $this->set('data', $this->data);
Your application /views/layouts/json.ctp file:
<?php header("Pragma: no-cache"); header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate"); header('Content-Type: text/x-json'); header("X-JSON: ".$content_for_layout); echo $content_for_layout; ?>
In your file app / views / controllername / ajax_test.ctp should only be:
<?php echo $js->object($status); ?>
Now, on your page, which is actually going to make an ajax call, it might look something like this: with jQuery code:
<div id='status'></div> <?php echo $form->create('Test', array('id'=>'testForm')), $form->input('message'), $form->end(); ?> <script type='text/javascript'> $('#testForm').submit(function(event) { event.preventDefault(); </script>
Tyler source share