Personally I do everything back and forth with JSON which ends up being a lot more flexible.
Here is the CodeIgniter Controller:
class Ajax extends Controller {
var $json_data=Array(
'error' => 1,
'html' => 'Ajax Error: Invalid Request'
);
function __construct() {
parent::Controller();
$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
$this->output->set_header('Expires: '.gmdate('D, d M Y H:i:s', time()).' GMT');
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
}
function do_something() {
$this->json_data['html'] = $this->load->view('someview', $_POST, true);
$this->json_data['error'] = 0;
$this->json_data['another_variable'] = 42;
}
function _output($output) {
echo json_encode($this->json_data);
}
}
Then in the script…
$.ajax({
url: '/ajax/do_something/',
type: 'POST',
data: {field: value},
dataType: 'json',
timeout: 8000,
success: success_function
});
function success_function(json) {
if (json.error)
alert(json.html);
else
$('#result_div').html(json.html);
if (json.another_variable == 42)
alert("I've found the secret of life!");
}
Obviously much more useful data can be passed back and forth. Everything in the ‘data’ object on the Javascript side will be in $_POST in CodeIgniter. I have used this setup for two sites now; one with a single AJAX controller that acts as router redirecting to mini-modules; another which uses several controllers just for ajax calls. If you are doing the latter you could setup a parent AJAX controller object which gets extended by all your AJAX controllers.