PHP Snippets

Sending Axios parameters with a POST request in PHP

Andrei Surdu Andrei Surdu ·

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.

Comments

Share your thoughts and join the conversation

Loading comments...

Leave a Comment

Your email will not be published

Comments are moderated and will appear after approval

0/2000