5

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?

1 Answer 1

8

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.

function enqueue_wpse_114600() 
{
    wp_register_script( 
         'my-ajax' // Handle
        , get_template_directory_uri() . '/js/ajax.js'
        , array( 'jquery' ) 
    );   
    wp_enqueue_script( 'my-ajax' );    
    wp_localize_script( 
         'my-ajax', // Handle
         'my_ajax', // Object name
         array( 
             'ajaxurl'     => admin_url( 'admin-ajax.php' ),
             'ajaxnonce'   => wp_create_nonce( 'ajax_validation' ) 
        ) 
    );
}

The JS would be like bellow, accessing the passed values with the Object Name, in this case my_ajax.any_value_you_passed.

jQuery( document ).ready( function( $ ) 
{ 
     var data = {
         action: 'countHits',
         security: my_ajax.ajaxnonce
     };   
     $.post( 
         my_ajax.ajaxurl, 
         data,                   
        function( response ) {
            if( !response.success )
            {
                // No data came back, maybe a security error
                if( !response.data ) console.log( 'AJAX ERROR: no response' );
                else console.dir( response.data.error );
            }
            else console.dir( response.data );
        }
     ); 
});

And in your Ajax action, check for the nonce with check_ajax_referer and use the functions wp_send_json_* that to send the result back (be a simple true or complex objects).

function countHits()
{
    check_ajax_referer( 'ajax_validation', 'security' );
    $ok = something();
    if( !ok )
        wp_send_json_error( array( 'error' => __( 'Not ok.' ) ) );
    else
        wp_send_json_success( $ok );
}
2
  • Thanks, This is similar to how i ended up integrating it :) im glad it worked Commented Sep 19, 2013 at 21:04
  • Perfectly explained.
    – Frank
    Commented Jan 24, 2020 at 9:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.