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` or XMLHttpRequest but still, I prefer Axios because of the many options it has, which are 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, no?

<?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 the $data variable contains both parameters item and type.

Extra Tip: Make sure to validate and sanitize any incoming data. Don’t trust anyone. See PHP filter types for more info.

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

  • Devin Walker 1 year ago

    Thanks! I ran into the same issue and was scratching my head. 🙂

  • James 1 year ago

    I spent so much time trying to get this working. Finally found the solution!!!

  • Helen Brenner 2 months ago

    Time saver! Thanks

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