WordPress Ajax callback function from plugin – OOP

Using PluginBoilerplate to write a plugin.
I need to make an ajax call.

I added to main plugin.php file, class to register scripts and handle ajax calls.

if ( ! class_exists( 'PoorMansNameSpaceAJAX' ) ) {

class PoorMansNameSpaceAJAX{
    public static $instance = null;
    public $nonce="";
    public $name="ajaxexample";
    public static function getInstance()
    {
        null === self::$instance AND self::$instance = new self;
        return self::$instance;
    }
    public function __construct(){
        # Could as well be: wp_enqueue_scripts or login_enqueue_scripts
        add_action( 'admin_enqueue_scripts', array( $this, 'scriptsEnqueue' ) );
        # Logged in users:
        add_action( 'wp_loaded', array( $this, 'scriptsRegister' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'scriptsLocalize' ) );
        add_action( 'admin_init', array( $this, 'ajaxRegister' ) );


    }
    public function scriptsRegister( $page ){
        $file="page-1.js";
        wp_register_script(
            $this->name ,
            WPBP_URLPATH . '/app/files/js/' . $file ,
            array('jquery')
        );
    }
    public function scriptsEnqueue( $page ){

        wp_enqueue_script( $this->name );
    }

    public function ajaxRegister() {
        add_action( "wp_ajax_{$this->name}_action",  array($this, 'ajaxexample'), '1' );
    }

    public function scriptsLocalize( $page ){
        wp_localize_script( $this->name, "{$this->name}Object", array(
            'ajaxurl'          => admin_url( 'admin-ajax.php' ),
            'action'           => "{$this->name}_action"
        ) );
    }

   public function ajaxexample(){
        ob_clean();

        echo json_encode( array(
            'success' => true
        ) );
        wp_die();   
    }
}
}

the class being called after vendor/autoload.php is included.

the main issue is that although the script is successfully registered, enqueued and localized, the ajax callback function is not taking action.

ajax call is returning empty response: html page with same content as the one im in. response.success is undefended.

    ( function( $, plugin ) {
           $(document).ready( function() {

            $('#moreroles').on('click', function(event) {
                event.preventDefault();
                /* Act on the event */
                var data = plugin;
                $.ajax({
                    url: plugin.ajax_url,
                    data: data,
                    beforeSend : function( d ) {
                        console.log( 'Before send', d );
                     }
                })
                .done( function( response, textStatus, jqXHR ) {
                    console.log( 'AJAX done', textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
                } )
                .fail( function( jqXHR, textStatus, errorThrown ) {
                    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
                } )
                .then( function( jqXHR, textStatus, errorThrown ) {
                    console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
                } );

            });
    } );
} )( jQuery, ajaxexampleObject || {});

1 Answer
1

WordPress can not load scripts after init hook.

PluginBoilerplate is missing the correct handling process for those kind of usage.
This OOP WP Plugin Boilerplate do it much better, and provide loader classes for admin and client.

Leave a Comment