Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active March 3, 2020 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/a53a5c982b9e6826369e2f37914ad77b to your computer and use it in GitHub Desktop.
Save tommcfarlin/a53a5c982b9e6826369e2f37914ad77b to your computer and use it in GitHub Desktop.
<?php
wp_enqueue_script(
'acme-security',
$this->plugin_url . 'assets/js/plugin.js',
[ 'jquery' ],
false,
true
);
wp_localize_script(
'acme-security',
'acme_ajax_object',
[
'ajax_url' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'acme-security-nonce' ),
]
);
$.get( acme_ajax_object.ajax_url, {
action: 'get_custom_data',
security: acme_ajax_object.security
}, function( response ) {
if ( undefined !== response.success && false === response.success ) {
return;
}
// Parse your response here.
});
<?php
public function get_custom_data() {
if ( ! check_ajax_referer( 'acme-security-nonce', 'security', false ) ) {
wp_send_json_error( 'Invalid security token sent.' );
wp_die();
}
// The rest of the function that does actual work.
}
@EricBusch
Copy link

Regarding this line:

if ( ! check_ajax_referer( 'acme-security-nonce', 'security' ) ) {

Without setting the 3rd $die parameter to false, the wp_send_json_error() and wp_die() calls are never made and the request just exits returning a 403.

In order to return the error message, you'll need this:

if ( ! check_ajax_referer( 'acme-security-nonce', 'security', false ) ) {

Hope this helps!

@tommcfarlin
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment