CakePHP and JQuery
A few months back I had the good fortune to come across JQuery. It change my life and made AJAX a breeze. In fact I simply don’t use straight Javascript any more, I only use JQuery.
About a month or two ago I also discovered the CakePHP development framework. Similarly, it seems to have changed my life (watch this space for my first CakePHP-based website).
Can you see where I’m going with this?
I wanted to be able to add JQuery to the CakePHP site that I am working on. It’s quite simple to do but I couldn’t really find anywhere that told me how to do it explicitly and I thought it might be worth explaining what I did here.
The first step is to have a functioning installation of CakePHP and a copy of JQuery.
You’ll need to put your JQuery file somewhere that CakePHP will be able to find it. As it turns out the best place would be /app/webroot/js/
Incidentally, this is also where you should include any external Javascript files. In the first instance I usually create a file called ‘javascript.js’ which includes all my Javascript calls.
So this leaves us with a directory structure that looks something like:
app/webroot/js/
jquery.js/
javascript.js/
Next, we need to include this file in the appropriate layout. If you haven’t done so already, it is most likely that this file will be called default.ctp and will live in app/views/layouts/. Now all you need to do is include the $javascript::link() method in your layout file.
In this case I’ve included the following line in my head tag:
< ?php echo $javascript->link(array('jquery.js', 'javascript.js')); ?>
And you’re done (of course it wouldn’t hurt you to go and read about the CakePHP Javascript Helper here). You can now proceed as usual and with the help of the HTML helper things might get easier yet.
REPLY))
This was of great help to me. Your tip got me started with cakephp and jquery. Thanks a lot.
REPLY))
I don’t know, this sounds so simple but I get this error:
Notice (8): Undefined variable: javascript [APP/views/layouts/default.ctp, line 14]
any help appreciated!
REPLY))
Hi ed,
That’s probably because you haven’t included the Javascript Helper in your controller.
You need to add
var $helpers = array('Javascript');to your controller. I generally add it to the AppController as it is a helper I use a lot.Of course it’s important to remember that you also need to add the ‘From’ and ‘Html’ helpers.
So generally speaking I include the following line in my AppController:
var $helpers = array('Form', 'Html', 'Javascript', 'Time');I’ll often add the Ajax and Paginator helper as well.
For more on helpers see: http://book.cakephp.org/view/98/Helpers