Codex

Attention Help us to improve the Codex by filling out our documentation survey!

Function Reference/check ajax referer

Contents

Description

This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.

Verifies the AJAX request to prevent processing requests external of the blog.

Usage

<?php check_ajax_referer$action$query_arg$die ?>

Parameters

$action
(string) (optional) Action nonce
Default: -1
$query_arg
(string) (optional) where to look for nonce in $_REQUEST (since 2.5)
Default: false
$die
(unknown) (optional)
Default: true

Return Values

(bool) 
If $die is set to false this function will return true / false

Examples

In your main file, set the nonce 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>


In your ajax file, check the referrer like this:

add_action( 'wp_ajax_my_action', 'my_action_function' );
function my_action_function() {
	check_ajax_referer( 'my-special-string', 'security' );
	echo $_POST['my_string'];
	die;
}

Notes

  • This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.
  • If $query_arg is not specified (i.e. defaults to false), then the function will look for the nonce in '_ajax_nonce'

Change Log

Source File

check_ajax_referer() is located in wp-includes/pluggable.php.

Related

Nonce functions: wp_explain_nonce(), wp_nonce_ays(), wp_nonce_field(), wp_nonce_ur(), wp_verify_nonce(), wp_create_nonce(), check_admin_referer(), check_ajax_referer(), wp_referer_field()

See also

External Resources

See also index of Function Reference and index of Template Tags.