Blend PHP and JavaScript in CakePHP

I guess it’s no big secret that you can easily serve JavaScript files with some PHP content, by using something like:

<script type="text/javascript" src="myscript.php"></script>

Let’s take a quick look at how this applies to CakePHP and what (hopefully) useful tricks you can accomplish by employing the following techniques…

First, we’d like to avoid any messy and ugly in-line JS and load all files by using the convenient $javascript->link() method.

We’ll create an empty view (views/users/test.ctp), for the sake of this demonstration and load some JS file:

$javascript->link('test_file.js.php', false);

Having the “.js.php” in the name of the file prevents cake from tacking on the “.js” extension by default, therefore our include in the head looks as we’d expect:

<script type="text/javascript" src="/js/test_file.js.php"></script>

Now, wouldn’t it be lovely to pass some variables from our Users Controller to this file?

Alright, let’s build a simple test() action:

function test() {
    $this->Session->write('User', 'My name is Charlie');
}

Since we are actually serving up a PHP file, rather than a plain JS file… we can blend JS and PHP to make some interesting things happen.
Here’s our test_file.js.php:

<?php
    session_name('CAKEPHP');
    session_start();
?>

alert('<?php echo $_SESSION['User']; ?>');

session_name(‘CAKEPHP’); is based on the session cookie name, which is set in config/core.php.
The rest of the file should pretty much self explanatory… we simply pop-up an alert box with “My name is Charlie”, which we’ve wrote to the session in the Users Controller above.
(Sorry, I couldn’t come up with a more boring example).

However, this opens up some interesting opportunities, such as dynamically setting values for your jQuery scripts, while maintaining very clean mark-up and avoiding any in-line JS.

P.S. AD7six pointed out that any .js file in your app/vendors/js/ can have PHP code in it, so you don’t need to use “.js.php” trick, however many IDE’s will give you a very quirky highlighting (to say the least) when you are editing PHP code in a .js file, but not the other way around. Either way you’ve got both options to play around with.

Related Posts

%d bloggers like this: