I have a few Ajax services that I’m setting up. All of them require being logged in so I’ve attached hooks into the “wp_ajax_[$service]”. The problem is when I call these services I just get a “0” response. I also get no record of anything in my php error log.

What I’m wondering is:

  1. Is there a way to hook into ALL Ajax requests and dump some debug information into the log file so I can get some more info out what is going on?
  2. Has anyone seen this problem before? Are there any tips about solving for this type of problem?

UPDATE:

Including code to give more context. First the the Javascript, it is:

ServiceCall ( 'get-action-template' , {'action' : action} , function(response) {// callback function});

and the ServiceCall function is:

function ServiceCall ( service , parameters , callback ) {
    console.log ('getTemplate was called: (' + service +', ' + parameters + ')' );

    //initialise a request object
    var requestObj = {};
    requestObj.response="ajax-response";
    requestObj.type="POST";
    requestObj.url =  my_config['ajax-service-list'][service]['url'];
    requestObj.data = $.extend ( requestObj.data , {
                                            'service': service,
                                            'request_parameters': JSON.stringify(parameters),
                                            'ajax_nonce': my_config['ajax-service-list'][service]['nonce']
    });
    requestObj.global = false;
    requestObj.timeout = 30000;
    requestObj.success = function ( r ) {
        alert ( "Success: " + JSON.stringify (r) );
        callback ( r );
    }
    requestObj.error = function ( r ) {
        console.log ("FAILURE WITH AJAX Call ( " + JSON.stringify (r) + ")");
    }
    $.ajax( requestObj );
}

This then generates the following message (taken from network panel in browser’s debugger):

debug

Finally, here’s the code for the handler function (which NEVER gets called):

public static function ajax_handler () {
    error_log ( "AJAX HANDLE"  ); 
    $service = $_POST['action'];
    $request_parameters = json_decode ($_POST['request_parameters']);
    if ( LG_Utility::key_from_hash ( self::$services_list , $service , false ) ) {
        $object = new self::$services_list[$service]['class'] ($service);
        $object->handle( $service , $request_parameters );
    } else {
        if (class_exists ('AppLogger') ) AppLogger::error ( "Trying to handle a service ({$service}) which is not registered!"); 
    }
}

I have validated, however, that it is hooked correctly to the wp_ajax_get-action-template event. The shorthand “proof” is using the popular “debug objects” plug-in I was able to validate that it was set. Here’s the whole PHP class that’s managing the AJAX transactions (some methods/consts removed for brevity):

 class LG_AjaxServiceManager
 {
   private static $services_list = array(
    'get-action-template' =>    array ( 'class' => 'LG_GetActionTemplate' , 'login_required' => true ),
    'some-other-service' =>     array ( 'class' => 'LG_FooBar' , 'login_required' => false )
   );
   public static function add_listeners () {
    foreach ( self::$services_list as $id => $service ) {
        add_action ( 'wp_ajax_' . $id , 'LG_AjaxServiceManager::ajax_handler' );
        if (class_exists ('AppLogger') ) AppLogger::log ( "Registering $id as an Ajax service" ); 
    }   
   } 
   public static function ajax_localize () {
    // add hook for script localisation; this is important so that JS scripts have nonce and URL information
    foreach ( self::$services_list as $id => $service ) {
        $service_url = wp_nonce_url ( admin_url ( 'admin-ajax.php?action="' . $id .'"' ) , self::AJAX_APP_NONCE_KEY . '_' . $id );
        preg_match ( '/.*action=%22(.*)%22&_wpnonce=(.*)/' , $service_url , $service_parts );
        self::$ajax_js_array [ $service_parts[1] ] = array ( 'nonce' => $service_parts[2] , 'url' => esc_url ( $service_url ) );
    }

    $localize = array (
            'SiteURL' => get_bloginfo ('url'),
            'AjaxURL' => admin_url ('admin-ajax.php'),
            'ajax-service-list' => self::$ajax_js_array
    );
    wp_enqueue_script ( 'jquery' );
    wp_enqueue_script ( self::JS_FILE_HANDLE  , plugins_url ( '/js/lg-ajax-client.js' , dirname(__FILE__)) , 'jquery' );

    wp_localize_script( self::JS_FILE_HANDLE , self::JS_NAMESPACE , $localize );

   }
   public static function ajax_handler () {
    error_log ( "AJAX HANDLE"  ); 
    $service = $_POST['action'];
    $request_parameters = json_decode ($_POST['request_parameters']);
    if ( LG_Utility::key_from_hash ( self::$services_list , $service , false ) ) {
        $object = new self::$services_list[$service]['class'] ($service);
        $object->handle( $service , $request_parameters );
    } else {
        if (class_exists ('AppLogger') ) AppLogger::error ( "Trying to handle a service ({$service}) which is not registered!"); 
    }
   }
}

2 Answers
2

According to the WordPress documentation, you should call die() at the end of your PHP function to return proper results.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *