CodeIgniter Ajax Layer CodeIgniter Ajax Layer codeigniter codeigniter

CodeIgniter Ajax Layer


It all depends on what you're doing. The easiest way, in my opinion, is not to have separate AJAX controllers and urls, but to detect the request in your controller and output something different than you normally would. The Input class has a function for this:

/** * Is ajax Request? * * Test to see if a request contains the HTTP_X_REQUESTED_WITH header * * @return  boolean */public function is_ajax_request(){    return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest');}

I prefer to use a constant:

/** * Is this an ajax request? * * @return      bool */define('AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');

Example usage in a controller method:

$data = $this->some_model->get();if ($this->input->is_ajax_request()){    // AJAX request stops here    exit(json_encode($data));}$this->load->view('my_view', $data);

This way, you don't have identical or similar application logic spread out through sevral different controllers, and your code can be more maintainable. For example, your standard HTML forms can post to the same location with AJAX and have different output, so it also helps make progressive enhancement easier and cleaner. In addition, you won't have "AJAX-only" URLs that you need to "hide" from the user.


I will attempt to offer a simple solution that I have used in the past. I am however, uncertain about your proficieny/familiarity with CodeIgniter, also this is my own "home-brewed" solution that I developed to deal with the issues in CodeIgniter.

I like CodeIgniter for its simplicity, and small foot print. But certain of its features I don't use: I don't use the provided database connection system, as I am a little bit of a control freak and SQL injection is so prevalent. So I have learned how to deviate within the framework for this reason.

In order to create a separate "layer" that houses AJAX processing and to keep it clean and tidy in implementation I just make a separate controller object who's specific job is to respond to AJAX requests. This way your "web page" controllers are separate from your "Ajax" controllers.

class Ajax extends CI_Controller{    function __construct(){ parent::__construct();}    function webserv(){ /* Your Web Service code here... */}}

Then you would direct your AJAX requests to this URL:

http://www.example.com/ajax/webserv/