HolaBook
HolaBook

Reputation: 27

How to receive Fetch() POST in php?

So i got this POST json method here, but can't understand how to get my json data

It's packed in BLOB which is packed in FormData

How to receive such POST in php? (and convert this FormData(Blob) back to json?)

JS

        const data = new FormData();
        const jsonBlob = new Blob([JSON.stringify(myJSON)], {type: "application/json"});
        data.append("data", jsonBlob);
        fetch(website,{
            method: "POST",
            body: data,
        }).then(resp=>{
            if(!resp.ok){
                const err = new Error("Error response");
                err.resp = resp;
                throw err;
            }
            console.log("OK");
        }).catch(err =>{
            console.error(err);
        })

I'm big noobo, so i can't even receive it

Seems like it works differently with fetch()

PHP

if(isset($_POST['data'])){

}

Upvotes: 0

Views: 1832

Answers (1)

Koala Yeung
Koala Yeung

Reputation: 7893

The simpliest way to send a JSON to server is to simply send it as the POST request body. There is no need to wrap it like a file. For example,

var myJSON = {
    hello: 'world',
    foo: 'bar',
};
fetch(website, {
    method: "POST",
    body: JSON.stringify(myJSON),
})

On server side, your message will be readable through the "php://input" stream. You can read it like an ordinary file:

$request_raw = file_get_contents('php://input');
$json_object = json_decode($request_raw);

You can save the below code as a PHP file and test it yourself. On load, it would send itself another POST reqeust, parse it as key-value pairs, return it to your browser and show it:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $request_raw = file_get_contents('php://input');
        $request = json_decode($request_raw);
        foreach ($request as $key => $value) {
                echo "{$key}: {$value}\n";
        }
        exit;
}

?>
<div id="result"></div>
<script>
var myJSON = {
    hello: 'world',
    foo: 'bar',
};
fetch(document.location.href, {
    method: "POST",
    body: JSON.stringify(myJSON),
}).then(resp => {
    if(!resp.ok){
        const err = new Error("Error response");
        err.resp = resp;
        throw err;
    }
    console.log("OK");
    return resp.text();
}).catch(err =>{
    console.error(err);
}).then(body => {
    document.getElementById('result').innerText = body;
});
</script>

Upvotes: 1

Related Questions