Ajax Handler v1.2

The Ajax Handler is a CakePHP Component that processes and handles AJAX requests. It determines what action should be dealt as an AJAX call, applies the appropriate filters, prepares the data for a response and responds with the appropriate headers.

Ajax Handler v1.2 (Log)
Uploaded: 11/05/2009
Requires: PHP 5, CakePHP 1.2
Tested On: PHP 5.2.5, CakePHP 1.2.5


View Manual:

Ajax Handler

Package: Component
Category: CakePHP
Views: 2,229

The Ajax Handler is a CakePHP Component that processes and handles AJAX requests. It determines what action should be dealt as an AJAX call, applies the appropriate filters, prepares the data for a response and responds with the appropriate headers.

Class Features:
  • Handles pre-defined Controller actions as AJAX
  • Formats the AJAX Post/Get into Controller $data values
  • Blackholes/Kills the request if the action is not called through AJAX
  • Respond with a success or failure message
  • Automatically format your data into JSON, XML, HTML or plain text
  • Responds with the correct Content-Type headers
  • Utilizes the Request Handler

Top

1 - Installation


To use AjaxHandler, add it to your $components array in your Controller. For a more precise setup, its good practice to place all your AJAX actions within a controller called Ajax. Additionally if you want extra security and validation, apply the Security component to your Controller.

class AjaxController extends AppController {
	var $components = array('AjaxHandler');
}


The next step is to tell the component which actions in the Controller should be handled as an AJAX call. You can pass the handle() method an argument of * to apply to all actions, or a argument separate list of action names (Similar to how Auth::allow() works). By default, the component does not handle any actions.

function beforeFilter() {
    parent::beforeFilter();
 
    $this->AjaxHandler->handle('*');
    // Or individual actions
    $this->AjaxHandler->handle('login', 'logout', 'postComment');
}
Top

2 - Response Output


You can use only 4 types of content to respond as, they are json, xml, html and text. By default all content is returned in JSON format, but you can tell which content types to use by passing the type as the first argument for respond() (more on this later).

Additionally all JSON and XML returns will have the following values: success, data and code. The success value would be a boolean true/false, if the current action was completed successfully or failed. The data value would contain any messages, errors, objects, arrays or data that you need to use in your scripts. Lastly we have the optional code value, which can be used to determine the severity of messages (example 0-9). Below is an example of each responses output:

{
    "success": true,
    "data": "Success!",
    "code": 1
}


<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <success>true</success>
    <data>
    	/* Your data */
    </data>
    <code>1</code>
</root>


All returned XML will be formatted by applying an arrays values as attributes to its parent element. If you want to use individual element tags instead, you would set the $xmlFormat variable to tags. For more information, read the CakePHP Cookbook on XML serialization.

$this->AjaxHandler->xmlFormat = 'tags';
Top

3 - Responding


While doing your logic in the action, you may want to mark the response as a success or failure and insert the respective data and code. You can do this by using the response() method. The first argument would be a boolean true/false, where a success is a true and a failure is a false. The second argument would be the data you would return; can be an array, string, object, int, basically anything! The last argument would be your associated code number or string.

// No data required, just a status
$this->AjaxHandler->response(true);
 
// Return the $data with the JSON
$this->AjaxHandler->response(true, $this->data);
 
// Action failed, apply code
$this->AjaxHandler->response(false, $this->data, -1);


Once you have set your response, you will need to respond that data back to the client / script. You would use the respond() method, which should always be placed at the end of your action to ensure that all logic has completed. The respond() method takes a first argument for its content type: json (default), xml, text, html. The second argument applies only to HTML responses and determines whether or not the view should be automatically rendered.

The respond() method generates the correct HTTP headers, formats and displays the output, so its best to use it!

$this->AjaxHandler->respond();
return;
 
// Return as XML
$this->AjaxHandler->respond('xml');
return;
Top

4 - Example Action


Below is an example Controller action utilizing the AjaxHandler. The action is used for logging in a user.

function login() {
    if ($this->AjaxHandler->valid($this->data['username'], true) && $this->AjaxHandler->valid($this->data['password'], true)) {
        if ($this->Auth->login($this->data)) {
        	$this->AjaxHandler->response(true, $this->data);
        } else {
        	$this->AjaxHandler->response(false, 'Username/password combo incorrect', 0);
        }
    } else {
    	$this->AjaxHandler->response(false, 'No username/password', -1);
    }
 
    $this->AjaxHandler->respond();
    return;
}
Top

5 - Example Javascript


Below is an example Javascript function used to trigger an AJAX call. I am using jQuery to call the AJAX and setting the dataType to json to return my content. Make sure your dataType is the same as the AJAX response or the response will fail!

function login() {
    var data = $("#UserLoginForm").serialize();
 
    $.ajax({
        type: "POST",
        url: "/ajax/login/",
        data: data,
        dataType: "json",
        success: function (response) {
            if (response.success == true) {
            	// Success!
            } else {
            	alert(response.data +" ("+ response.code ")");
            }
        }
    });
 
    return false;
}
Read the whole documentation? Download the script now and try it yourself! Return to the Top