Post to Php file using Vanilla Javascript

Viewed 847

I am posting to PHP file an OBJECT, the question is, I am not using name="" like when we do it inside the forms, but Instead, I am posting an Object, look:

    const done = async obj => {
    console.log("sending JSON to PHP...");
     await fetch("myFile.php",
        {
            method: "post",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(obj)
        }
    )
}
let obj = {
    email: "ahmad@example.com",
    message: "salam"
}
const send = async (obj)=>{
    let response = await done(obj);
}
send(obj);

The question is, How the PHP will resolve the posted arguments?

here is what I've tried:

$email = $_POST['email'];
$message = $_POST['message'];

but as usual, this isn't working.

[EDIT]:

Extra question: is it important to send the POSTED data as JSON format? Is it important to do that while using the fetch API?

2 Answers

Try something like this

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

$email = $data['email'];
$message = $data['message'];

As you have used stringify, your php file will receive a string representation of your json object. So you will have to use json_decode to convert the string to a php object.

$json = file_get_contents('php://input');
$data = json_decode($json);
$email = $data->email;

Further clarification: If the request body contains string representation of JSON, content-type header will be text/plain, even if the Content-Type is set to application/json. So, in php file, you will have to read the raw text in body with file_get_content first as string and the convert it to php json object.

Related