sebacruz
2/8/2012 - 10:02 PM

Ajax Template Controller for Kohana 3.1

Ajax Template Controller for Kohana 3.1

<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * Ajax Controller Template.
 *
 * @author Sergei Gladkovskiy <smgladkovskiy@gmail.com>
 */
abstract class Controller_Ajax extends Controller {

	/**
	 * Allow fake AJAX via POST, also ensure this request
	 * came via XHR.
	 *
	 * @return  void
	 * @uses    AJAX::post_override()
	 * @uses    AJAX::ensure()
	 */
	public function before()
	{
		AJAX::post_override($this->request);
		AJAX::ensure($this->request);
		parent::before();
	}
	
	/**
	 * Add AJAX headers to response. Doing so here rather
	 * than in Controller_Ajax::before() allows for more
	 * flexibility within actions.
	 *
	 * @return  void
	 * @uses    AJAX::set_headers()
	 */
	public function after()
	{
		AJAX::set_headers($this->response);
	}
	
}
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * AJAX Helper
 *
 * @author  Sergei Gladkovskiy <smgladkovskiy@gmail.com>
 * @author  Luke Morton
 */
class AJAX {

	/**
	 * Ensure request is AJAX.
	 *
	 * @param   Request
	 * @return  void
	 */
	public static function ensure(Request $request)
	{
		// Ajax Request check
		if ( ! $request->is_ajax()
			AND Kohana::$environment == Kohana::PRODUCTION)
		{
			throw new HTTP_Exception_403;
		}
	}
	
	/**
	 * Allow POST override of AJAX.
	 *
	 * @param   Request
	 * @return  void
	 */
	public static function post_override(Request $request)
	{
		if ($request->method() === HTTP_Request::POST
			AND $request->post('is_ajax'))
		{
			$request->requested_with('xmlhttprequest');
		}
	}
	
	/**
	 * Set AJAX Headers.
	 *
	 * @param   Response
	 * @return  void
	 */
	public static function set_headers(Response $response)
	{
		$response->headers('Content-Type',
			'application/json; charset='.Kohana::$charset);
	}
	
}