The first thing is to inline the nonce so that you can use it in the script that calls the ajax action.
// plugin or theme php file
wp_enqueue_script(
'your-script-handle',
'url/to/your/script.js',
array( 'jquery' ),
null,
true
);
wp_add_inline_script(
'your-script-handle',
'const YourAjaxConfig = ' . json_encode( array(
'ajax' => array(
'url' => admin_url( 'admin-ajax.php' ),
'action' => 'test_process',
'nonce' => wp_create_nonce( 'test_process_nonce' ),
),
) ),
'before'
);
Get the nonce value from the config object and pass it along the ajax call.
// script.js
jQuery.post(
YourAjaxConfig.ajax.url,
{
action: YourAjaxConfig.ajax.action,
_ajax_nonce: YourAjaxConfig.ajax.nonce,
},
function($data) {
// do something with the response
}
);
Then use for example check_ajax_referer() to check that the request has a valid nonce in it.
// ajax handler php file
add_action( 'wp_ajax_test_process', 'test_process' );
function test_process() {
if ( ! check_ajax_referer( 'test_process_nonce', false, false ) ) {
wp_send_json_error( 'Invalid nonce', 400 );
}
// code...
wp_send_json_success( 'test_process done' );
}
P.S. using WP AJAX is a bit old school nowadays. You could consider using WP REST instead. See the handbook for REST nonce example.