Passing JavaScript variable into snippet

Hi guys, Im triying to do the same tasks explained here but for some reason, I’ve been failing miserably and cannot find the source of my error, I have a resource with the following snippet call:

[[!#POST.courseId]]
[[!#GET.courseId]]

[[!createIntent?
&post=[[!#POST]]
&courseId=[[!#POST.courseId]]
&disCode=[[!#POST.disCode]]
&successRedirect=23
&failRedirect=23
&currency=[[++chargeCurrency]]
&reBuy=[[!#POST.reBuy]]
&unitId=[[!#POST.unitId]]
]]

And I’m trying to call it from a fetch call like this

fetch(“https://192.168.0.104/intent.html”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”
},
data: JSON.stringify(purchase)
})

where purchase is

  1. courseId: “18”

  2. disCode: undefined

  3. items: Array(1)

  4. 0: {id: “xl-tshirt”}

And I can see the data traveling on the request inside the dev tools

But inside the snippet, courseId it’s always null and the print of POST on the resources comes clean, what could I be missing?

The way you’re submitting the data (POST with an application/json content type and a JSON string data body) cannot be read by $_GET or $_POST in PHP - that’s only available in the raw body input.

For example, like this:

$raw = file_get_contents('php://input');
$input = json_decode($raw, true);

$input is then an array with keys courseId, disCode, etc. Assuming the input is properly formatted - which you should always make sure, as users can’t be trusted. :wink:

1 Like

Thanks a lot, as usual, you saved me, just adding that made the trick to get the data correctly, but i’m wondering is this the right way to do it? because I’m thinking a final implementation should use a proper rest endpoint

It’s a fairly common way to do things in the bigger PHP world. JSON request bodies are easy to do on the client-side (javascript) and easy enough to access server-side too, so it’s not a wrong way to do it.

1 Like