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?