CodeIgniter AJAX Helper
This is a quick post on how to recognize AJAX Requests.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
?>
Copy the following code into a file. Save the file as ajax_helper.php and save in your application/helpers/ folder.
Load it if you need if by:
Normal loading
This is pretty much how we normally include helpers. This is the best approach unless you would use the ajax helper most of the time.
$this->load->helper('ajax');
Autoloading
Open your config.php file located at application/config/. Look for this line.
$autoload['helper'] = array();
Add yours to the list
$autoload['helper'] = array('ajax');
You should not add _helper when adding it to the autoload['helper'] array.
Categories: How To, Web Development
Tags: codeigniter, php
5 Comments
Thorpe Obazee
@erick. No problem. I’m glad this post helped you.
November 26th 2009
Mei
great stuff, but an better implementation (IMHO) is to use it as an extension of the input class. Have it as a method in MY_Input.php and it will be loaded automatically.
It can then be used as $this->input->isAjax() in your controllers.
December 11th 2009
Mei
@Mei.There are numerous ways to do this and yours is a good way.
December 17th 2009
Elizabeth
I have been trying to use this, and it works just fine when I load it in the controller. But I am unable to autoload this helper and the standard Session library. I get a “headers already sent” error every time I try to do both. I can autoload either one alone, or I can autoload one and load the other in the controllers.
Any ideas?
January 31st 2010


erick
Thanks sa helper
November 26th 2009