I created a Vanilla JS Ajax handler as follows:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {

xhttp.open("POST", ajaxurl, true);

And put this into the theme functions.php file:

add_action('wp_ajax_lalala', 'lalala_ajax_test');

function lalala_ajax_test(){
    $reponse = array('test');
    header("Content-Type: application/json");
    echo json_encode($response);

And I am getting this in the browser console:

POST https://example.com/wp-admin/admin-ajax.php 400 (Bad Request)

When I change the request to GET, as follows:

xhttp.open("GET", '/wp-admin/admin-ajax.php?action=lalala', true);

It works like a summer sunshine.

So, the error must be related with how the action parameter is passed when doing the request in POST mode.

1 Answer 1


Well this is very probably going to help someone else sometime so here it goes:

Not setting the request to application/x-www-form-urlencoded makes the POST body behave like a string. So PHP does not recognize $_POST variables. To make that happen we need:

xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

So the whole thing goes like:

xhttp.open("POST", ajaxurl, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

And then it behaves as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.