admin-ajax Firing Error 400 When Logged In

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.

Topic ajax php Wordpress javascript

Category Web


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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.