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.
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
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.
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