Ah yes, the ol’ admin-ajax error 400 issue. I have looked here and here and here for a solution and none of those fixed my problem. So before this is marked as a duplicate, please just hear me out.
My admin-ajax link looks like so:
<script type="text/javascript"> var ajaxurl = "https://full-url.com/wp-admin/admin-ajax.php"; </script>
My AJAX call looks like this:
var data = {
action: 'get_events'
};
jQuery.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(data){
console.log(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(xhr.status);
console.log(thrownError);
}
});
And inside my functions.php, I have the following:
add_action('get_events', 'get_events_func');
add_action('wp_ajax_nopriv_get_events', 'get_events_func');
function get_events_func() {
echo 'please work';
exit();
}
This works perfectly fine when I am logged out of the website, but once I am logged in, it throws an error 400. Did I set up that wp_ajax_nopriv_ hook wrong? That’s the only thing I can think of.
The error response I am getting is simply:
XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, abort: ƒ, onreadystatechange: ƒ, …}
abort: ƒ ()
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: ƒ ()
ontimeout: null
readyState: 4
response: "0"
responseText: "0"
responseType: ""
responseURL: "https://full-url.com/wp-admin/admin-ajax.php"
responseXML: null
status: 400
statusText: ""
timeout: 0
upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials: false
__proto__: XMLHttpRequest
400
undefined
Any help is really appreciated. Thank you.
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
Did I set up that
wp_ajax_nopriv_hook wrong?
No, you did not. But that hook is for logged-out or unregistered users only.
For logged-in users, the hook is wp_ajax_<action>.
So you just need to change the add_action('get_events' in your code to add_action('wp_ajax_get_events', and the error 400 would be gone:
add_action('wp_ajax_get_events', 'get_events_func'); // for logged-in users
add_action('wp_ajax_nopriv_get_events', 'get_events_func'); // for logged-out users
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