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.
<?php>
class TestsController extends AppController {
public $uses = null;
public function index(){
$this->layout='default';
}
}
?>
<html>
<head>
</head>
<body>
<?php>
echo $content_for_layout;
?>
</body>
</html>
There are two ways to include JQuery into CakePHP. You can choose to include it from either CakePHP layout file or view file.
<head>
<?php>
echo $javascript->link("jquery-1.4.2.min");
?>
</head>
<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.
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.
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.