-1

Say I have this AJAX sent via jQuery to a PHP server

$.ajax({
    url: woocommerce_admin_meta_boxes.ajax_url,
    data: data,
    type: 'POST',
    success: function (res) {
        if (res.success) {
            location.reload();
        }
    }
});

and data looks like this

data = {
    order_id: woocommerce_admin_meta_boxes.post_id,
    order_items : [
        {
            order_item_id: 69420,
            amount: 420
        },
        {
            order_item_id: 42069,
            amount: 69
        }
    ]
};

What I have found out is by using PHP's $_POST, I can access the order id like this

$order_id = $_POST['order_id'];

However, I am not sure of how I can access stuff inside order_items from data. From what I've seen in this stackoverflow post, there's a PHP function called json_decode(), but I'm not so sure of how to use this together with AJAX or $_POST.

2

1 Answer 1

2

$.ajax() doesn't use JSON encoding, it sends URL-encoded format, so there's no need to use json_decode().

To access the nested data, just use ordinary array accessing in the $_POST variable.

foreach ($_POST['order_items'] as $item) {
    echo "Item ID: " . $item['order_item_id'] . "<br>";
    echo "Amount: " . $item['amount'] . "<br>";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.