Skip to content

Instantly share code, notes, and snippets.

@lukemorton
Forked from smgladkovskiy/Controller_Ajax_Template.php
Created August 4, 2011 09:12
Show Gist options
  • Save lukemorton/1124802 to your computer and use it in GitHub Desktop.
Save lukemorton/1124802 to your computer and use it in GitHub Desktop.
Ajax Template Controller for Kohana 3.1
<?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);
}
}
<?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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment