Using Jquery in CakePHP

In case you need to use jquery in cakephp. (not really ‘in case’, but more of ‘use it!’)

3 Things you need to take care of.

  1.  In your App Controller (if you want to use it for the whole app else you can put it at a specific controller)
    var $helpers = array( 'Javascript' );
  2.  In your default layout or your view
    link('https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false);
    I’m using google’s CDN for my jquery js file
  3. Test if your jquery works. Place this in your view (.ctp) file.
    $(document).ready(function(){
    $(“a”).click(function(event){
    alert(“Thanks for visiting!”);
    });
    });

Number 3 above is of course just for testing. Once you get it working you should place your js files in the webroot folder so that it’s not messy. Else you’ll be dependent on the where the view is when you change your javascript.



Leave a comment