CodeIgniter Ajax Layer

I've been doing a lot of research in ajax but I can't seem to find much about creating a separate ajax layer with codeigniter ... I've seen ajax controllers in the directory tree of people doing tutorial videos on codeigniter just never got a real explanation. I guess it will promote encapsulation and only show to users with javascript enabled and the like, just not sure how to implement it in a controller for use in my own projects.

+3


source to share


2 answers


It all depends on what you are doing. The easiest way, in my opinion, is not to have separate controllers and AJAX urls, but to detect the request in your controller and output something different than usual. 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 the same or similar application logic propagated across different controllers, and your code can be more convenient. For example, your standard HTML forms can be hosted in the same place as AJAX and have different outputs, which also makes progressive enhancement easier and easier . Also, you won't have "AJAX only URLs" that you need to "hide" from the user.

+5


source


I will try to offer a simple solution that I have used in the past. However, I'm not sure about your experience / familiarity with CodeIgniter, it is also my own "home" solution that I developed to solve problems in CodeIgniter.

I love CodeIgniter for its simplicity and small print. But I don’t use some of its features: I don’t use the provided database connection system, as I’m a bit of a control freak and SQL injection is so common. So I learned how to stray within the framework for this reason.

To create a separate "layer" that hosts the AJAX processing, and to keep it clean and tidy in implementation, I simply create a separate controller object to which a specific task should respond to AJAX requests. This way your "webpage" controllers are decoupled from your "Ajax" controllers.



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

      

Then you will route your AJAX requests to this url:

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

0


source







All Articles