Skip to content

Instantly share code, notes, and snippets.

@hipsterjazzbo
Created March 16, 2011 04:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hipsterjazzbo/872008 to your computer and use it in GitHub Desktop.
Save hipsterjazzbo/872008 to your computer and use it in GitHub Desktop.
A CodeIgniter controller to enable dynamic AJAX access to models from views.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax extends CI_Controller {
function __construct()
{
parent::__construct();
}
/**
* Dynamic AJAX access to models from views.
*
* In jQuery, can be used by:
*
* $.post('ajax/MODEL/METHOD', { arg1: val, arg2: val }, function(data) {
* // Do something with returned data
* }, 'json');
*
**/
function _remap($model, $params = array())
{
// Method will be first array item; we'll ignore the rest (if any).
$method = array_shift($params);
// Load the model requested. CI will throw a nice error for us if it doesn't exist.
$this->load->model($model);
// Call the model and method requested, and pass in any $_POST data that was sent.
$output = call_user_func_array(array($this->$model, $method), $_POST);
// 'echo' rather than 'return', as this is an AJAX controller, and encode as JSON
echo json_encode($output);
}
}
/* End of file ajax.php */
/* Location: ./application/controllers/ajax.php */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment