0

I created a Vanilla JS Ajax handler as follows:

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

xhttp.open("POST", ajaxurl, true);
xhttp.send("action=lalala");
}

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);
    exit();
}

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);
xhttp.send();

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

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');
xhttp.send("action=lalala");

And then it behaves as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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