0

I'm using Gravity Forms, and I want to use a jQuery script to set some defaults in my form. Whenever the user dropdown changes, fetch all the roles belonging to the chosen user. I thought the simplest way to do this would be a call to the REST API, but I am having problems setting the nonce so that I can pull out the user's data. How does one set the nonce so that it is available?

Here is my code in functions.php, where i tried to create a nonce.

function abc_enqueue_nonce() {
    wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest_nonce' ) ) );
}

add_action("wp_enqueue_scripts", "abc_enqueue_nonce");
wp_enqueue_script( 'abc_enqueue_nonce' );

Then I wanted to call it in the jQuery:

$.ajax({
    url: wpApiSettings.root + 'wp/v2/users/3',
    method: 'GET',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
    },
    success: function(data){
        console.log(data);
    }
}).done( function ( response ) {
    console.log( response );
});
  • edit your question to show the code where you register the script abc_enqueue_nonce. – mmm May 3 '18 at 5:44

Your Answer

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

Browse other questions tagged or ask your own question.