This helper library makes it easier to handle AJAX requests in WordPress plugins. Mainly for personal use.
Define action:
$exampleAction = ajaw_v1_CreateAction('ws_do_something')
->handler(array($this, 'myAjaxCallback'))
->requiredCap('manage_options')
->method('post')
->requiredParam('foo')
->optionalParam('bar', 'default value')
->register();
Call from JavaScript:
AjawV1.getAction('ws_do_something').post(
{
'foo': '...'
},
function(response) {
console.log(response);
}
);
admin-ajax.php
URL and nonce to JS. $builder->requiredParam('foo', 'int')
$builder->optionalParam('meaningOfLife', 42, 'int')
$_GET
, $_POST
and $_REQUEST
. $builder->withoutNonce()
$builder->requiredCap('manage_options');
$builder->optionalParam('things', 1, 'int', function($value) {
if ($value > 10) {
return new WP_Error(
'excessive_things',
'Too many things!',
400 //HTTP status code.
);
}
})
$builder->method('post')
Backwards compatibility. In theory, this library should be compatible with WP 4.1+.