1

I'm a little confused about how nonces work with ajax requests. It looks like I'm supposed to use this: https://codex.wordpress.org/Function_Reference/check_ajax_referer

The request looks like this:

<?php
//Set Your Nonce
$ajax_nonce = wp_create_nonce( "my-special-string" );
?>

<script type="text/javascript">
jQuery(document).ready(function($){
    var data = {
        action: 'my_action',
        security: '<?php echo $ajax_nonce; ?>',
        my_string: 'Hello World!'
    };
    $.post(ajaxurl, data, function(response) {
        alert("Response: " + response);
    });
});
</script>

But this approach seems to assume that your JavaScript is mixed in with your PHP, which I is a practice that I like to avoid. When I write an ajax request for a plugin, I use admin_url( 'admin-ajax.php') to separate out the request so it's a bit cleaner to read.

How would I use a nonce in this situation? Do I pass it within the admin_url( 'admin-ajax.php') bit?

  • this is a code styling question that is not actually wordpress specific – Mark Kaplun Sep 24 '16 at 3:20
2

You can localize your script and pass the nonce and ajax url to the script.
Learn more about script localization.

function wpse_206839() {

    // Register our script just like we would enqueue it - for WordPress references
    wp_register_script( 'my-special-script', 'directory/my-special-script.js', array( 'jquery' ), false, true );

    // Create any data in PHP that we may need to use in our JS file
    $local_arr = array(
        'ajaxurl'   => admin_url( 'admin-ajax.php' ),
        'security'  => wp_create_nonce( 'my-special-string' )
    );

    // Assign that data to our script as an JS object
    wp_localize_script( 'my-special-script', 'specialObj', $local_arr );

    // Enqueue our script
    wp_enqueue_script( 'my-special-script' );

}
add_action( 'wp_enqueue_scripts', 'wpse_206839' );

This will allow us to access our nonce in JS as console.log( specialObj.security );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.