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

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

  • Devin Walker 2 years ago

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

  • James 2 years ago

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

  • Helen Brenner 1 year ago

    Time saver! Thanks

Cancel reply

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