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.
add_action('get_events',
should beadd_action('wp_ajax_get_events',
..admin-ajax.php
, consider using the REST API instead. It's well-documented and you can do things like retrieving Posts, Pages, CPT posts, custom taxonomy terms, etc. What's more, you'd get a better response body/text (well, at least it's not simply a0
..) when an error is encountered during an API request, so debugging would become easier than with the ol'admin-ajax.php
.. :)