3

I want to use check_ajax_referer() to verify a WP_nonce field using AJAX. Here you can find my html element.

<input type="hidden" name="login_nonce" value="<?= wp_create_nonce('login_nonce'); ?>"/>

Using jQuery I'm sending all the values from input fields to a POST request:

request = $.ajax({
  type: 'POST',
  url: 'handle-login.php',
  data: {
    user: $('input[name="login_username"]').val(),
    pass: $('input[name="login_password"]').val(),
    security: $('input[name="login_nonce"]').val()
  },
  dataType: 'json'
});

In handle-login.php I'm try doing the following:

require_once $_SERVER['DOCUMENT_ROOT'].'/wp-load.php';

$return = array();
if( check_ajax_referer( 'login_nonce', $_POST['security'], false ) )
    $return['nonce'] = $_POST['login_nonce'];

echo $return

But in return I'll get nothing.. Someone knows what is up?

5

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('login_nonce', '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.

1

I have been having the same problems and I solved using another related ajax function: Just changing your

check_ajax_referer( 'login_nonce', $_POST['security'], false )

to

wp_verify_nonce( $_POST['security'], 'login_nonce' )

seems to work and return true / false correctly. About if it's more secure one way or other I have found this info:

wp_verify_nonce vs check_admin_referer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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