NF_AJAX_REST_Controller

A controller extensions for mapping REST requests to an admin-ajax action.

Defined (1)

The class is defined in the following location(s).

/includes/AJAX/REST/Controller.php  
  1. abstract class NF_AJAX_REST_Controller extends NF_Abstracts_Controller 
  2. /** 
  3. * The name of the admin-ajax action. 
  4. * @var string 
  5. */ 
  6. protected $action; 
  7.  
  8. /** 
  9. * Setup admin-ajax to access the endpoint router. 
  10. */ 
  11. public function __construct() 
  12. if( $this->action ) { 
  13. add_action('wp_ajax_' . $this->action, array($this, 'route')); 
  14.  
  15. /** 
  16. * Map admin-ajax requests to the corresponding method callback. 
  17. */ 
  18. public function route() 
  19. register_shutdown_function( array( $this, 'shutdown' ) ); 
  20.  
  21. $method = strtolower( $_SERVER['REQUEST_METHOD'] ); 
  22.  
  23. if( ! method_exists( $this, $method ) ) { 
  24. $this->_errors[] = __( 'Endpoint does not exist.', 'ninja-forms' ); 
  25. $this->_respond(); 
  26.  
  27. $request_data = $this->get_request_data(); 
  28.  
  29. try { 
  30. $data = $this->$method($request_data); 
  31. $this->_respond( $data ); 
  32. } catch( Exception $e ) { 
  33. $this->_errors[] = $e->getMessage(); 
  34. $this->_respond(); 
  35.  
  36. /** 
  37. * [OVERRIDE THIS] Get sanitized request data for use in method callbacks. 
  38. * @return array 
  39. */ 
  40. protected function get_request_data() 
  41. // This section intentionally left blank. 
  42.  
  43. /** 
  44. * [Example] FORM ID 
  45. */ 
  46. // if( isset( $_REQUEST[ 'form_id' ] ) && $_REQUEST[ 'form_id' ] ) { 
  47. // $request_data[ 'form_id' ] = absint( $_REQUEST[ 'form_id' ] ); 
  48. // } 
  49.  
  50. return array(); 
  51.  
  52. /** 
  53. * Returns debugging data when a fatal error is triggered. 
  54. */ 
  55. public function shutdown() 
  56. $error = error_get_last(); 
  57. if( $error !== NULL && in_array( $error[ 'type' ], array( E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR ) ) ) { 
  58.  
  59. $this->_errors[ 'form' ][ 'last' ] = __( 'The server encountered an error during processing.', 'ninja-forms' ); 
  60.  
  61. if( current_user_can( 'manage_options' ) && isset( $error[ 'message' ] ) ) { 
  62. $this->_errors[ 'form' ][ 'last_admin' ] = '<pre>' . $error[ 'message' ] . '</pre>'; 
  63.  
  64. $this->_errors[ 'last' ] = $error; 
  65. $this->_respond();