Using ajax + nonce

Hello,

I’m trying to send Ajax request with nonce.

My nonce is generated in setup.php and sended to my JS via bundle( 'app' )->localize();

In my ajax function wp_verify_nonce is always returning false.

am I missing something ?

Thanks :slight_smile:

Please share the actual code

Please share the actual code

bundle( 'admin-communication' )->enqueue();
bundle( 'admin-communication' )->localize(
	'api',
	[
		'ajax_url'                 => admin_url( 'admin-ajax.php' ),
		'nonce_product_send_email' => wp_create_nonce( 'product_send_email' ),
	]
);
fetch(api.ajax_url, {
  method: 'POST',
  credentials: 'same-origin',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: new URLSearchParams({
    action: 'acd_product_send_mail',
    // eslint-disable-next-line no-undef
    nonce: api.nonce_product_send_email,
  }),
}).then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(err => console.log(err))
  .finally(() => {
  });
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'product_send_email' ) ) { // phpcs:ignore
    wp_send_json_error();
}
1 Like

Try:
window.api.nonce_product_send_email
instead

Edit : finally not working, I don’t know why !

nonce: window.api.nonce_product_send_email,

You also need to use:
window.api.ajax_url

Try logging the nonce in your action hook with syslog for example.

In setup.php : 2a917e242c
In my JS file (console.log) : 2a917e242c
In ajax function (php) : [nonce] => 2a917e242c