admin-ajax.php doesn’t work when using POST data and Axios

The issue here, I think, is how axios works. Not WordPress. But you’re absolutely correct to want to use a POST request here.

By default I believe axios sends data in a POST request as JSON in the body. To get JSON in the body of the request in PHP you need to do this (from here):

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

The problem with that is that for the wp_ajax_ hooks to work, WordPress looks for the action in $_REQUEST['action']. This won’t be set if the action name is part of the request body, since $_REQUEST isn’t populated when the data is sent as JSON.

I believe that if you want to send POST data in axios the way a form does, and access it with $_POST or $_REQUEST, then you need to send it as FormData in the script:

var data = new FormData();

data.append('email', '[email protected]');
data.append('action', 'newsletter');

axios
    .post('/wp-admin/admin-ajax.php', data)
    .then(response => {
        console.log(response.data);
    });

PS: Just so you’re aware, this syntax: response => {, won’t work in any version of IE.

Leave a Comment