Cakephp 2.x using AJAX (Jquery)

Cakephp is a great framework to integrate with AJAX calls. 

This will go through the basic steps you need to get this up and running. 

The overview is as follows:

Pages/main (this will load first)
Pages/call (this will be called from mail and return data into the main view)

# 1 > Pages Controller

In the pages controller create 2 actions (functions)

function main() {
function call() {
     $this->log('I loaded'); //you can tail -f /app/tmp/error.log and view that this page is actually getting loaded from main
     $array = array(1, 2, 3); //showing that we can move arrays of data through ajax
     $this->set('array', $array); 
     $this->layout = false; //since we are loading our main which has a layout, this doesn't need a layout (or put a layout that is dedicated to these views)

# 2 > Main VIEW

Our main view will be the first to load and using JQUERY/AJAX it will then call 'function call()' and display the contents


<div id="content">
content will be replaced here

type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: "<?= $this->webroot; ?>Pages/call",
data: "HELLO",
success: function (data) {
//alert(data); //used for testing
error: function (result) {


# 3 > Call VIEW

Create a view for call.ctp. This will be displayed in the div id=content from the main view
-> This is great since you can setup this view opening Pages/call directly. When you are happy with it, you can then display within main


<?php foreach ($array as $each): ?>
<?= $each; ?>
<?php endforeach; ?>

# 4 > Done

So simple to load a page and quickly inject html content from another page into a div. 

Obvious this is a simple example, but imagine instead of loading all the information in one load you have 'elements' being injected via AJAX. 

This will make your pages smaller and will load quicker. 


# 5 > Security

After you have your app running it is good to add some security.

An easy way is to use 'Prefixes' for all of your AJAX calls. 
-> Simply add 'ajax_' before your function name in your controller which is called from the main 
-> Change function call() => function ajax_call()

Then in your beforeFilter (appController) add:

if (isset($this->params->params['prefix'])) {
if ($this->params->params['prefix'] == 'ajax') {
$this->layout = false; //or create a dedicated ajax layout
//Force to the same session which is already being used
//add other Security proceedures here

Other Instructions

Below are many other instructions that show you how to use your UpdateCase application