I have run into an issue with nonces becoming invalid, and being unable to refresh to a new nonce. In my example I have a Facebook Connect button, and a Facebook Disconnect button, each with their own nonce.
Once either one of these button is pressed, an AJAX call is made, and the other button is sent through AJAX and displayed on the page instead.
For sake of the example, we're starting with the Facebook Connect button.
<button type="button" id="facebook-connect-button" class="facebook-button" data-nonce="<?php echo wp_create_nonce('ns-social-facebook-authentication'); ?>"> <?php _e('Connect to', NS_USER_SYSTEM_TEXTDOMAIN); ?> Facebook </button>
After this button is pressed, an AJAX call is made, which verifies the data-nonce property like so:
check_ajax_referer( 'ns-social-facebook-authentication', '_nonce' );
No problems here, this works perfectly and my hooked function is working perfectly.
After this function has ran, it returns the Facebook Disconnect button that looks like this, and replaces the original button.
<button type="button" id="facebook-disconnect-button" class="facebook-disconnect-button" data-nonce="<?php echo wp_create_nonce('ns-social-facebook-disconnect'); ?>"> <?php _e('Disconnect from Facebook', NS_USER_SYSTEM_TEXTDOMAIN); ?> </button>
After pressing this button, everything works fine like before, and this time, the Facebook Connect button is called again though AJAX. Now here's when the issue starts.
This new returned button contains the same nonce, which is now invalid and returns a 403 error, since it's already been used before.
It looks like returning the button through AJAX does not refresh the nonce, even though it's already been used.
I have also tried displaying both buttons on the page, and returning just a new nonce with AJAX every time a button is clicked, but still, it keeps returning the same nonce for each of the buttons respectively.
Why is this happening and how can I fix this issue?
check_ajax_referer()will check in the ´_nonce´ field within the request and not for the data-nonce value on assigned to your button, please see the docs: codex.wordpress.org/Function_Reference/check_ajax_referer. On the other hand,
wp_create_nonce()uses the current time so the nonce generated on page load and the one generated on the ajax call should be different, can you share the response for your ajax call?