Sending Axios parameters with a POST request in PHP

Using a library like Axios to create complex AJAX requests is simple and easy. Of course, we can use `fetch` but still, I prefer Axios because of the many options it has, which is lightweight, well documented, and stable.

Recently I tried to use it by creating a POST request. On the server-side, I have WordPress, which obviously is backed up by PHP. The JS code looks like this:


axios.post(`${window.ajaxurl}?action=my_action`, {
    item: {some: object},
    type: 'products'
})
    .then(response => {
        const {data} = response;

        console.log(response);
    })
    .catch(err => {
        console.error(err);
    });

Pretty simple. On the server-side I tried to access the superglobal $_POST. I did a post request in the end, not?

<?php 
public function process(): void
{
   $item = $_POST['item']; // does not work
}

Looks right, but it does not work. The $item variable is empty. $_POST is completely an empty array.
If I would change this to a axios.get then I would easily be able to access it using the $_GET global.

The solution:

The solution is to use php://input stream. Here is how I did it:

public function process(): void
{
    $request_body = file_get_contents('php://input');
    $data = json_decode($request_body, true);


    $item = $data['item']; // Works!
}

Cool! Now it works and $data variable contains both parameters item and type.

Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

    Your email address will not be published. Required fields are marked *