Mohit Paudyal
Mohit Paudyal

Reputation: 17

how to capture javascript request payload in php

I am sending a request payload from a javascript function like such

  onApprove: function(data, actions) {
    return actions.order.capture().then(function(details) {
      fetch('https://www.eg.com/tq.php', {
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          orderID: id // i get the id here.
        })
      });
      return window.location.href = "https://www.https://www.eg.com/tq.php";
    });
  }
}).render('#paypal-button-container');

In my PHP file I want to retrieve that id. I did :

$data = $_POST['orderID'];

AND

$data = json_decode($data); 
echo $data->orderID; 

AND

even tried changing the url to x-www-form-urlencoded. Still I do not get the value. When I check on the payload I do see the orderID, I also see a 200 OK. Can someone show me what i'm doing wrong? I did research stackoverflow and still can't get this to work. Please help.

Upvotes: 1

Views: 664

Answers (1)

sujameslin
sujameslin

Reputation: 181

fetch function will send GET request if you don't pass method: POST in config explicitly. That's why you're not getting orderID from $_POST in server-side.

Insert method: "POST" in config like this.

fetch("https://www.eg.com/tq.php", {
  method: "POST",
  headers: {
    "content-type": "application/json"
  },
  body: JSON.stringify({
    orderID: id // i get the id here.
  })
});

Upvotes: 4

Related Questions