Reusing P2’s ajaxUrl Short-Circuits Other AJAX Requests

I just spent awhile tracking down some odd AJAX behavior that was puzzling me, so I thought I’d share the solution. I was working on a plugin to extend P2 and my AJAX requests were always responding with -1. After a lot of digging and some trial-and-error, I figured out that it was happening because I was using P2’s ajaxUrl variable.

Normally it’d be better to reuse the existing variable than create a redundant one, but P2 adds a ‘p2ajax=true‘ parameter to the URL, which triggers a condition in P2Ajax::dispatch() which short-circuits any other AJAX calls.

if ( defined('DOING_AJAX') && DOING_AJAX && isset( $_REQUEST['p2ajax'] ) ) {
	add_action( 'admin_init', array( 'P2Ajax', 'dispatch' ) );
}

// [...]

function dispatch() {
	$action = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : '';

	do_action( "p2_ajax", $action );
	if ( is_callable( array( 'P2Ajax', $action ) ) )
		call_user_func( array( 'P2Ajax', $action ) );
	else
		die( '-1' );
	exit;
}

The solution is to use _wpUtilSettings.ajax.url from Core’s utils script, or do something like this in the request:

ajaxUrl.replace( 'p2ajax=true', 'p2ajax=false' )

Leave a Reply

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