Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress plugin to test which kinds of callbacks work for AJAX: namespaced, closures, class based, static vs. non static, etc.
<?php
namespace WCM\Tests;
/**
* Plugin Name: Ajax Namespace Callback Test
*/
/**
* MarkUp
*/
add_action( 'admin_notices', function()
{
echo <<<EOF
<form method="get" action="wcmtest">
<label for="ajax-test" class="howto">AJAX Test Input - watch your console<br>
<input type="text" name="ajax-test" id="ajax-test" />
</label>
</form>
EOF;
} );
/**
* Script/AJAX send/receive
*/
add_action( 'admin_print_footer_scripts', function() {
?>
<script type="text/javascript">
( function( $ ) {
"use strict";
$( '#ajax-test' ).on( 'keyup', function( event ) {
var $this = $( this );
console.log( $this.val() );
$.ajax( {
url : ajaxurl,
data : {
action : "wcmtest_action",
//_ajax_nonce : <?php wp_create_nonce( "wcmtest_action" ); ?>,
value : $this.val()
},
beforeSend : function( d ) {
console.log( "before send", d );
}
} )
.done( function( response, textStatus, jqXHR ) {
console.log( response );
} )
.fail( function( jqXHR, textStatus, errorThrown ) {
console.log( jqXHR, textStatus, errorThrown );
} );
} )
.delay( 500 );
} )( jQuery || {} );
</script>
<?php
}, 100 );
# ############ Different methods of registering a callback
# Closure: works
/*add_action( 'wp_ajax_wcmtest_action', function( $data )
{
// Value: WCM\Tests\{closure}
$data['function'] = __FUNCTION__;
wp_send_json_success( $data );
} );*/
# Namespaced function - hard coded: works
# add_action( 'wp_ajax_wcmtest_action', '\WCM\Tests\AjaxTestCbNamspacedHardcoded' );
function AjaxTestCbNamspacedHardcoded( $data )
{
$data['function'] = __FUNCTION__;
wp_send_json_success( $data );
}
# Namespaced, but not hard coded: works
# add_action( 'wp_ajax_wcmtest_action', __NAMESPACE__.'\AjaxTestCbNamespaced' );
function AjaxTestCbNamespaced( $data )
{
$data['function'] = __FUNCTION__;
wp_send_json_success( $data );
}
# Plain function, no namespace: works
# add_action( 'wp_ajax_wcmtest_action', 'AjaxTestCbPlain' );
function AjaxTestCbPlain( $data )
{
$data['function'] = __FUNCTION__;
wp_send_json_success( $data );
}
# Class based
add_action( 'plugins_loaded', function() {
new Foo;
} );
class Foo
{
public function __construct()
{
# normal: works
#add_action( 'wp_ajax_wcmtest_action', array( $this, 'AjaxTestCbPlain' ) );
# static: works
#add_action( 'wp_ajax_wcmtest_action', array( __CLASS__, 'AjaxTestCbStatic' ) );
}
public function AjaxTestCbPlain( $data )
{
// Value: WCM\Tests\Foo::AjaxTestCbPlain
$data['function'] = __METHOD__;
wp_send_json_success( $data );
}
public static function AjaxTestCbStatic( $data )
{
// Value: WCM\Tests\Foo::AjaxTestCbStatic
$data['function'] = __METHOD__;
wp_send_json_success( $data );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.