2

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
    If you are getting a 0 response, it means either action is missing or doesn't match any hooked action. I don't think you are correctly passing the action in your JS. – Milo Jan 18 '17 at 4:05
  • the data object has 'action' inside of it equals to "ajaxexample_action". it suppose to direct ajaxexample function on the PoorMansNameSpaceAJAX class. – Amit Rahav Jan 18 '17 at 4:48
  • According to your localize call, action is a property of ajaxexampleObject. – Milo Jan 18 '17 at 4:59
  • @Milo take a look at my editing. i referred plugin variable as ajaxexampleObject. – Amit Rahav Jan 18 '17 at 5:06
  • A simple test to see if your function is correctly hooked is to manually visit admin-ajax.php URL in your browser and pass the action as a GET var, like yourdomain.com/wp-admin/admin-ajax.php?action=ajaxexample_action. – Milo Jan 18 '17 at 5:10
-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.

  • This is incorrect. Scripts can be registered and enqueued all the way up through the wp_enqueue_styles action (and even a little afterwards, actually). In a typical request, that's more that 17 high-profile actions after init, as listed by the WordPress Action Reference. – bosco Mar 29 '17 at 1:48
  • @bosco so is it just the wp_ajax_{$this->name}_action for your understanding? – Amit Rahav Mar 29 '17 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.