How-to implement admin Ajax inside an admin WP_List_Table?

I am new to WordPress if someone will help me I will be very appreciate.

There is parameter ajax “true” but in docs. wasn’t said how to implement Ajax using WP_List_Table Class?

parent::__construct( array(
            'singular'  => 'user',     //singular name of the listed records
            'plural'    => 'users',    //plural name of the listed records
            'ajax'      => true        //does this table support ajax?
        ) );

Related posts

Leave a Reply

2 comments

  1. In the parent __construct args if ajax is set to true the js_vars will be output in the footer of the page.

    /**
         * Constructor. The child class should call this constructor from it's own constructor
         *
         * @param array $args An associative array with information about the current table
         * @access protected
         */
        function __construct( $args = array() ) {
            $args = wp_parse_args( $args, array(
                'plural' => '',
                'singular' => '',
                'ajax' => false
            ) );
    
            $screen = get_current_screen();
    
            add_filter( "manage_{$screen->id}_columns", array( &$this, 'get_columns' ), 0 );
    
            if ( !$args['plural'] )
                $args['plural'] = $screen->base;
    
            $args['plural'] = sanitize_key( $args['plural'] );
            $args['singular'] = sanitize_key( $args['singular'] );
    
            $this->_args = $args;
    
            if ( $args['ajax'] ) {
                // wp_enqueue_script( 'list-table' );
                add_action( 'admin_footer', array( &$this, '_js_vars' ) );
            }
        }
    

    The default javascript variables that get output in the footer are defined in the js_vars function:

    /**
         * Send required variables to JavaScript land
         *
         * @access private
         */
        function _js_vars() {
            $current_screen = get_current_screen();
    
            $args = array(
                'class'  => get_class( $this ),
                'screen' => array(
                    'id'   => $current_screen->id,
                    'base' => $current_screen->base,
                )
            );
    
            printf( "<script type='text/javascript'>list_args = %s;</script>n", json_encode( $args ) );
        }
    
  2. Have you already taken a look on the WP_List_Table class Methods? There’s ajax_response()

    • ajax_response() – use it to implement your custom permission rule set

      public function ajax_response()
      {
          return current_user_can( 'manage_options' );
      }
      
    • ajax_response() – handle your ajax callbacks/actions.
    • _js_vars() – every var that you want to use inside your custom ajax callbacks. Works similar to wp_localize_script().