Im creating a visit/page views counter with ajax,jquery and php, I have been reading a few articles that recommend the use of nonces for data manipulation through ajax, however i am not sure if i need to integrate the use of nonces for my simple counter?
my code looks somewhat like this;
jquery
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {action: 'countHits', status: 'true'},
});
php
//ajax functions
add_action('wp_ajax_countHits', 'countHits');
add_action('wp_ajax_nopriv_countHits', 'countHits');
function countHits() {
if($_POST['status'] != "") {
$status= $_POST['status'];
if(!isset($_COOKIE['UNIQUEUSER'] && $status == 'true'){
$uniqueUser= get_option('stats');
$uniqueUser['uniqueUser']+=1;
update_option('stats', $uniqueUser);
}
die();
}
So as you can see it is very simple, do I need to use nonces for each ajax request?(i have two separate request in my jquery which return variables one for false one for true) furthermore, if I wanted to implement nonces how would i go about doing that?
I think required would mean that “it doesn’t work without it”. It will work, but the question is of security and best practices. Even if it doesn’t seem necessary, it’s better to play in the safe side and do it always.
You have to enqueue your JavaScript like bellow, passing PHP values (like the admin Ajax URL and the nonce) with
wp_localize_script
.The JS would be like bellow, accessing the passed values with the Object Name, in this case
my_ajax.any_value_you_passed
.And in your Ajax action, check for the nonce with
check_ajax_referer
and use the functionswp_send_json_*
that to send the result back (be a simpletrue
or complex objects).