Tuesday, April 19, 2011

CakePHP : Embed dynamic Javascript code

Code is using CakePHP (lower)1.2 version

Step 1: Add a line to bottom of config/routes.php

Router::parseExtensions('js');

* Note: For CakePHP (upper)1.2 version and above has its own default mappings, so may not need to include this line, pls try and error.

Step 2: Create a plain layout for javascript page, views/layouts/js/default.ctp

<?php echo $content_for_layout;


Step 3: Add action and requestHandler in controllers/feeds_controller.php
class FeedsController extends AppController
{
 var $name = 'feeds';
 var $components = array('RequestHandler');
 
 function get() {
  
 }
}

Step 4(a): For PHP testing purpose, views/feeds/get.ctp

<?php echo "Hello world";


Step 4(b): Actual dynamic javascript page, views/feeds/js/get.ctp

<?php echo "document.write('Hello world');";


Step 5: Now, You can paste this javascript code to wherever you want.

<script type="text/javascript" src="http://yourdomain.com/feeds/get.js"></script>


Refer site:
Request Handling
Integrate PHP Into JavaScript in CakePHP
 

1 comment: