CodeIgniter Forums
A base controller for AJAX only - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: External Resources (https://forum.codeigniter.com/forumdisplay.php?fid=7)
+--- Forum: Addins (https://forum.codeigniter.com/forumdisplay.php?fid=13)
+--- Thread: A base controller for AJAX only (/showthread.php?tid=69942)



A base controller for AJAX only - dave friend - 02-01-2018

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.


RE: A base controller for AJAX only - skunkbad - 02-01-2018

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;
}

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