Do I require the use of nonce?

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 );
}

Leave a Comment