AJAX nonce with check_ajax_referer()

Difficult to say for sure where the mistake is as you have not mentioned about your add_action('wp_ajax_my_function','whatever_callback');which I think you missed out on that. But your question is missing info in this respect.

This is how I would get on about this:

In your functions.php file or similar:

add_action(wp_ajax_handle_login, 'handle_login_ajax');
add_action(wp_ajax_nopriv_handle_login, 'handle_login_ajax');

Make sure your handle-login.php file is declared on your main php file from your plugin or theme such as functions.php

require_once plugin_dir_path(__FILE__) . 'handle-login.php';

You should declare nonce variables and the ajax url right after your js file hook, you will be able to access these after:

wp_enqueue_script('wccajs',plugin_dir_url( dirname(__FILE__) ) . 'login.js',array('jquery'),'1.0',false);

wp_localize_script('wccajs','MyAjax',array( 
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'security' => wp_create_nonce('handle_login')
) );

In your handle-login.php file:

function handle_login_ajax(){
    check_ajax_referer('handle_login', 'security');
    $return = array();
    echo $return;
    wp_die(); // You missed this too
}

Your Javascript file:

function send_stuff_to_server(){

var data = {
    'action': 'handle_login', // missed this same as your action hook wp_ajax_{handle_login}
    'security': MyAjax.security // We can access it this way
}

$.post(MyAjax.ajax_url, data, function (callBack) {
      console.log(callBack); // Will return nonce
});

}

Hope this helps.

Leave a Comment