Welcome Guest, Not a member yet? Register   Sign In
A base controller for AJAX only
#1

(This post was last modified: 02-01-2018, 10:09 AM by dave friend.)

I have created a controller that extends CI_Controller and is designed to be the base class for Controllers that only accept xmlhttprequest (AJAX) requests.

It can be found in this repository on GitHub.

Any questions, comments, or insults are welcome.
Reply
#2

Although I'm not the captain of the REST train, this could possibly be more useful if it checked for all of the REST methods, and checked for input from php://input. A little snippet of my (non-CodeIgniter) class:

PHP Code:
/**
 * For put or patch requests, the input data will be in php://input,
 * unless this is a POST disguised as a PUT or PATCH.
 */
protected function _fetch_input_data()
{
    
// If there's a post array, just return it
    
if( in_array$this->method, ['put','patch'] ) && ! empty( $_POST ) )
        return 
$_POST;

    
// Otherwise, check PHP's input stream
    
if( in_array$this->method, ['put','patch'] ) )
    {
        
$input $this->_cache_php_input();

        if( ! empty( 
$input ) )
            return 
$this->_process_php_input();
    }

    return 
NULL;
}

// -----------------------------------------------------------------------

/**
 * Cache contents of php://input
 */
protected function _cache_php_input()
{
    ! 
is_null$this->_php_input ) OR 
        
$this->_php_input file_get_contents('php://input');

    return 
$this->_php_input;
}

// -----------------------------------------------------------------------

/**
 * Parse, decode, unserialize, or otherwise process the php input.
 */
protected function _process_php_input()
{
    switch( 
$this->content_type )
    {
        case 
'application/x-www-form-urlencoded':
            
parse_str$this->_php_input $vars );
            break;
        case 
'application/json':
            
$vars json_decode$this->_php_inputTRUE);
            break;
        case 
'application/vnd.php.serialized':
            
$vars unserialize$this->_php_input );
            break;
        default:
            
$vars $this->_php_input;
    }
    
    return 
$vars;
}

// ----------------------------------------------------------------------- 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB