Created
March 16, 2011 04:08
-
-
Save hipsterjazzbo/872008 to your computer and use it in GitHub Desktop.
A CodeIgniter controller to enable dynamic AJAX access to models from views.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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