Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter Ajax Layer

I've been doing a lot of researching on ajax but I cant seem to find much about creating a separate ajax layer with codeigniter... I've seen ajax controllers in the directory tree of people performing tutorial videos on codeigniter, just never gotten a real explanation. I'm assuming its to promote encapsulation and to show only to users with javascript enabled and such, just not sure how to go about implementing it in a controller for use in my own projects.

like image 422
newguy13 Avatar asked Jun 24 '26 14:06

newguy13


1 Answers

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.

like image 70
Wesley Murch Avatar answered Jun 26 '26 05:06

Wesley Murch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!