SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

CakePHP and JQuery ( 1 )

In this tutorial, we will go through basic steps to use Jquery in CakePHP. We will also highlight some common mistakes. The final task is to alert a string using JQuery.

Preparation

  • Download CakePHP, in this tutorial we are using CakePHP 1.3.2.
  • Download JQuery, in this tutorial we are using JQuery 1.4.2. Place JQuery lib into "app/webroot/js" directory.
  • Create a test controller at "app/controllers/tests_controller.php", because we don't need a model for this tutorial, we will set it to null. Create function index() for view file:

<?php>
 class TestsController extends AppController {
	 public  $uses =  null;
	 public function index(){
	 	$this->layout='default';
	 }
 }
?>
 
  • Create view folder and file at "app/views/tests/index.ctp", since there is no content needed, we can keep index.ctp blank.
  • Create a default layout at "app/views/layouts/default.ctp":
<html>
    <head>
    </head>
    <body>
    <?php>
        echo $content_for_layout;
    ?>
    </body>
</html>

Include JQuery

There are two ways to include JQuery into CakePHP. You can choose to include it from either CakePHP layout file or view file.

  • To include JQuery from CakePHP layout file is pretty straightfoward. Inside "app/views/layouts/default.ctp", add codes to head section :
<head>
 
 <?php>
 echo $javascript->link("jquery-1.4.2.min"); 
 ?>
 
</head>
  • To include JQuery from CakePHP view file which is "index.ctp". Firstly, we need to add a varialbe $scripts_for_layout to layout file:
<head>
 
 <?php>
 echo $scripts_for_layout;
 ?>
 
</head>

Then inside view file "app/views/tests/index.ctp", we include JQuery:

<?php>
 echo $javascript->link("jquery-1.4.2.min",false); 
?>

for $javascript->link() function,if you forget to set second parameter to be false explicitly, or you set it to be true, CakePHP will output script tag inline, so JQuery will be included from body part of the html document, which is not advisable.

Alert string

This is the final step where you can test out if you have included JQuery successfully into CakePHP. add javascript codes to head part of the layout file "app/views/layouts/default.ctp":

<head>
 
 ***other codes ***
 
<script type="text/javascript">
	$(document).ready(function () {
		alert('JQuery is succesfully included');
	});
</script>
 
 
 ***other codes ***
 
</head>

Now open you test page http://your-host/test/index, you should be able to see an alert string.

The end

Thank you for reading this tutorial, please give us your feedback by comments. Next tutorial, we will show you how to use JQuery in CakePHP to accomplish certain tasks. Please stay tuned, if you like our tutorial, please follow us on Twitter and help spread the word.