If you plan to make more active use of AJAX action calls, it may be appropriate to use the "overkill" route rather than the "inelegant" route. The following method configures your application to handle AJAX requests pretty elegantly.
In routes.php add:
Router::parseExtensions('json');
Create a new json directory in app/views/layouts/ and a new default.ctp layout in the new directory:
<?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; ?>
Create a new json directory in app/views/bookmarks/ and a new view delete.ctp in the new directory:
<?php $response = $ok ? array( 'status'=>1, 'message'=>__('Bookmark deleted',true)) : array( 'status'=>0, 'message'=>__('Could not delete bookmark',true)); echo $javascript->object($response);
Controller:
class BookmarksController extends AppController() { var $components = array('RequestHandler'); function beforeFilter() { parent::beforeFilter(); $this->RequestHandler->setContent('json', 'text/x-json'); } function delete( $id ) { $ok = $this->Bookmark->del($id); $this->set( compact($ok)); if (! $this->RequestHandler->isAjax()) $this->redirect(array('action'=>'index'),303,true); } }
On the pages from which AJAX is called, you must change the AJAX requests from /bookmarks/delete/1234 to /bookmarks/delete/1234.json .
It also gives you the ability to handle non-AJAX calls with /bookmarks/delete/1234 with the app/views/bookmarks/delete.ctp .
Any further actions that you want to handle through AJAX and JSON would add the views to the app/views/bookmarks/json/ directory.
source share