NaszvadiG
4/17/2014 - 9:03 AM

Ajax_Controller.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Application AJAX Controller.
 *
 * @package 	CodeIgniter
 * @category	Controllers
 * @author		Sepehr Lajevardi <me@sepehr.ws>
 * @link		https://github.com/sepehr/ci-base-controllers
 */
abstract class Ajax_Controller extends Base_Controller {

	/**
	 * Ajax request corresponding model name.
	 */
	protected $_model = FALSE;

	// ------------------------------------------------------------------------

	/**
	 * AJAX controller constructor.
	 */
	public function __construct()
	{
		parent::__construct();

		Events::trigger('before_ajax_controller');

		// Restrict to Ajax requests only
		if ( ! $this->input->is_ajax_request())
		{
			show_error('You are not allowed to view this page :)', 403, '403 Unauthorized Access');
		}

		// Load model if set
		$this->_model AND $this->load->model($this->_model);

		Events::trigger('after_ajax_controller');
		log_message('debug', 'AJAX Controller Class Initialized.');
	}

	// ------------------------------------------------------------------------

	/**
	 * Request response generator.
	 */
	public function response($response = array(), $add_success = TRUE, $code = '200')
	{
		is_object($response) AND $response = (array) $response;
		is_array($response)  OR  $response = array('message' => $response);

		// Prepare response
		$add_success AND $response = array('success' => 'true') + $response;

		// Using CI output class API to enbale caching for ajax requests
		$this->output
			->set_status_header($code)
			->set_content_type('application/json')
			->set_output(json_encode($response))
			->_display();

		exit();
	}

	// ------------------------------------------------------------------------

	/**
	 * Request error generator.
	 */
	public function error($message = 'Invalid request!', $code = '400')
	{
		$this->output
			->set_status_header($code)
			->set_content_type('application/json')
			->set_output(json_encode(array('error' => $message)))
			->_display();

		exit();
	}

}
// End of Ajax_Controller class

/* End of file Ajax_Controller.php */
/* Location: ./application/core/Ajax_Controller.php */