-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.

waifu-master
  • 23
  • 1
  • 4
  • Send data like JSON.stringify(data) in ajax and decode this in php using json_decode() – Haresh Makwana Oct 06 '20 at 05:23
  • Refer this post https://stackoverflow.com/questions/15986235/how-to-use-json-stringify-and-json-decode-properly/37625282#:~:text=When%20you%20save%20some%20data,following%20code%20worked%20for%20me.&text=from%20the%20question)-,%24data%20%3D%20json_decode(%24_POST%5B%22JSONfullInfoArray%22%5D)%3B,%24_POST%5B%22JSONfullInfoArray%22%5D)%3B – Haresh Makwana Oct 06 '20 at 05:24

1 Answers1

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>";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612