how to send Ajax request in wordpress backend
Question
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);
})
0
1 month
0 Answers
9 views
0
Leave an answer
You must login or register to add a new answer .