how to send Ajax request in wordpress backend

On the fronted the wp_localize_script seems to be working as when I view the source I can see the nonce.

wp_localize_script('scripts', 'myAjax', array(
    'root_url' => get_site_url(),
    'ajaxurl'  => admin_url( 'admin-ajax.php' ),
    'nonce'    => wp_create_nonce('wp_rest')
));

For example, when I try get a list of users when logged into the wordpress backend I get a 401 unauthorised error. When I view the source my nonce is not there, only on the frontend.

$.ajax({
        url: 'https://example.com/wp-json/wp/v2/users/',
        method: 'GET',
        beforeSend: (xhr) => {
        xhr.setRequestHeader('X-WP-Nonce', myAjax.nonce);
        },
    })
    .done(function (data) {
        console.log(data);
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus + ': ' + errorThrown);
        console.warn(jqXHR.responseText);
    })

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

When you enqueue or localize a script you’re doing it specifically for the front end or the admin. If you want to enqueue or localize a script in both, you have to specifically do it for both.

This is used to enqueue/localize for the front end

add_action( 'wp_enqueue_scripts', 'your_function_front' );
your_function_front() {
     wp_localize_script('scripts', 'myAjax', array(
         'root_url' => get_site_url(),
         'ajaxurl'  => admin_url( 'admin-ajax.php' ),
         'nonce'    => wp_create_nonce('wp_rest')
     ));
}

But for the backend you have to also add:

add_action( 'admin_enqueue_scripts', 'your_function_admin' );
your_function_admin() {
     wp_localize_script('scripts', 'myAjax', array(
         'root_url' => get_site_url(),
         'ajaxurl'  => admin_url( 'admin-ajax.php' ),
         'nonce'    => wp_create_nonce('wp_rest')
     ));
}

So if it works in the front end, then you’ve probably done the first one correctly, and you now just have to do it for the back end. Just remember to name your functions to something that’ll make sense in your plugin/theme.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x